【发布时间】:2020-05-22 21:48:54
【问题描述】:
这里是playground
我正在尝试使参数成为可选参数,但仍然让 typescript 了解函数返回的内容。
如果定义了参数,则返回参数的类型。否则 - 如果没有提供参数,函数将返回 undefined。
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
这是有道理的。不过,我找到了conditional types,虽然我可以做类似的事情
const meh = <T>(initialData?: T): { data: T ? T : undefined} => {
,但它给出了语法错误。
【问题讨论】:
标签: typescript typescript-typings