how define a dynamic type with optional argument ? #17219
Answered
by
JiatLn
baixiaoyu2997
asked this question in
Q&A
-
我想要这种效果可以实现吗?如果useTest传入了参数text,那么getXXX可以不传入参数,但是如果useTest没有传入参数text,那么getXXX必须传入参数,也就是说getXXX的参数能否为动态可选的? const useTest=(useTestOptions?:{text?:string})=>{
const getXXX=(options?:{text?:string})=>{
return options.text || text
}
return {
getXXX
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
JiatLn
Oct 9, 2022
Replies: 3 comments 4 replies
-
const useTest = <T = undefined>(arg1?: T) => {
const getXXX = (arg2?: number) => {
// do some things
}
return getXXX as T extends undefined ? (arg2: number) => any : () => any
}
const getXXX = useTest(1)
const getXXX2 = useTest() |
Beta Was this translation helpful? Give feedback.
2 replies
-
hope it could work~ function useTest<T extends { text: string }>(options: { text: string }): { getXXX: () => string }
function useTest<T extends Omit<Record<string, any>, 'text'>>(options: any): { getXXX: (options: { text: string }) => string }
function useTest<T extends Omit<Record<string, any>, 'text'>>(): { getXXX: (options: { text: string }) => string }
function useTest(useTestOptions: { text?: string } = {}) {
const getXXX = (options?: { text: string }) => {
return options.text || useTestOptions.text
}
return {
getXXX
}
}
const { getXXX: f1 } = useTest({ text: '123' })
const { getXXX: f2 } = useTest()
const { getXXX: f3 } = useTest({})
f1()
f2({ 'text': '123' })
// @ts-expect-error
f2()
// @ts-expect-error
f3() |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
baixiaoyu2997
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hope it could work~