[英]Typescript access nested conditional type
I am trying to access the nested type b given the following type definition and that a is not null:我正在尝试根据以下类型定义访问嵌套类型 b 并且 a 不为空:
type Abc = {
a: {
b: number
} | null
}
However, the following code causes an error: Property 'b' does not exist on type '{ b: number; } | null'.ts(2339)
但是,以下代码会导致错误:
Property 'b' does not exist on type '{ b: number; } | null'.ts(2339)
Property 'b' does not exist on type '{ b: number; } | null'.ts(2339)
const test: Abc["a"]["b"] = 3;
You could change it to:您可以将其更改为:
const test: NonNullable<Abc["a"]>["b"] = 3;
That's a bit of a mouthful though.不过还是有点口无遮拦。 You could also consider splitting it into a couple interfaces, and referring to the inner one directly:
您也可以考虑将其拆分为几个接口,并直接引用内部接口:
interface Thing {
b: number
}
type Abc = {
a: Thing | null
}
const test: Thing["b"] = 3;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.