这是游乐场
我试图使参数成为可选参数,但仍使打字稿理解从函数返回的内容。
如果定义了param,则返回param的类型。否则-如果未提供参数,则函数将返回未定义。
const meh = <T>(initialData?: T): { data: T | undefined} => {
if (initialData) {
return { data: initialData }
}
return {
data: undefined
}
}
const res1: undefined = meh().data // is ok:
type ResType = {
hello: string
}
const res2: ResType = meh<ResType>({ hello: 'hello'}).data.hello // TS error: Object is possibly undefined
有道理。虽然,我找到了条件类型,但我可以做类似的事情
const meh = <T>(initialData?: T): { data: T ? T : undefined} => {
,但是会产生语法错误。
您可以使用函数重载吗?
function meh(): { data: undefined };
function meh<T>(initialData: T): { data: T };
function meh<T>(initialData?: T): any {
if (initialData) {
return { data: initialData }
}
return {
data: undefined
}
}
type ResType = {
hello: string
}
const res1: ResType = meh<ResType>({ hello: 'hello'}).data
const res2: undefined = meh().data
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句