【发布时间】:2021-05-26 21:25:41
【问题描述】:
使用打字稿,当函数返回一个具有可能为空属性的对象时。为什么在这些内部属性上使用 typeguard 不允许 typescript 推断出内部 prop 在保护之后不能为 null?
这是一个最小的例子。 Try it
interface DatabaseResponse {
settings: string | null
}
interface MainResponse {
settings: string
}
const retrieveFromDatabase = (): DatabaseResponse => {
return {
settings: 'always a string but lets pretend it could be null sometimes'
}
}
const main = (): MainResponse | Error => {
const data = retrieveFromDatabase()
if (data.settings === null) {
throw new Error()
}
return data
}
main函数返回的错误是
Type 'DatabaseResponse' is not assignable to type 'MainResponse | Error'.
Type 'DatabaseResponse' is not assignable to type 'MainResponse'.
Types of property 'settings' are incompatible.
Type 'string | null' is not assignable to type 'string'.
Type 'null' is not assignable to type 'string'.
【问题讨论】:
-
这是 TypeScript 的设计限制和可能的功能请求,请参阅 microsoft/TypeScript#42384 获取信息,它甚至可能在某个时候将其变为语言(microsoft/TypeScript#38839 上的活动将修复它)
-
感谢@jcatz 提供的信息
标签: typescript typeguards