假设我在Typescript 中有这样的类型:
type State = {
one?: string;
two?: {
three?: {
four?: string;
five?: string;
six: number
},
seven: string
}
}
在只需要four
的情况下,如何通过重复使用State
来创建新的类型?其余的应该保持不变.
我认为我应该使用Required
实用程序类型,但我不确定如何将其应用于特定的嵌套属性.
Why I'm asking. Context:个
一般而言,我有一个类似于State[]
的State
数组,并且在某个点上,Ifilter
和map
通过呈现属性four
(某个id)来陈述,如下所示:
const states: State[] = [...];
states
.filter((state) => state.two?.three?.four && valid(state.two?.three?.four))
.map((state) => mapFour(state.two.three.four))
还有编译器抱怨mapFour
中的state.two.three.four
可能是undefined
的问题,因为type narrowing doesn't flow through scopes.
因此,我需要编写一个显式类型保护注释,如下所示:
.filter((state):state is MyNewTypeWhereFourIsNotOptinal => ...)
个
这就是为什么我问如何创建一个需要一些深度嵌套属性的新类型.