我正在尝试访问给定以下类型定义的嵌套类型 b 并且 a 不为空:
type Abc = {
a: {
b: number
} | null
}
但是,以下代码会导致错误: 类型 '{ b: number; 上不存在属性 'b'; } | null'.ts(2339)
const test: Abc["a"]["b"] = 3;
最佳答案
您可以将其更改为:
const test: NonNullable<Abc["a"]>["b"] = 3;
虽然这有点拗口。您还可以考虑将其拆分为几个接口(interface),并直接引用内部接口(interface):
interface Thing {
b: number
}
type Abc = {
a: Thing | null
}
const test: Thing["b"] = 3;
关于javascript - Typescript 访问嵌套条件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64147236/