If I have a TypeScript type defined as follows:
type State = {
one?: string;
two?: {
three?: {
four?: string;
five?: string;
six: number
},
seven: string
}
}
Is there a way to create a new type based on State
where only the property four
is required, while keeping the rest of the structure unchanged?
I believe that the Required
utility type should be used, but I am unsure how to specifically target the nested property.
My Reason for Asking:
In my scenario, I have an array of State
objects represented as State[]
. At some point, I filter and map these states based on the presence of the four
property (some ID), like so:
const states: State[] = [...];
states
.filter((state) => state.two?.three?.four && valid(state.two?.three?.four))
.map((state) => mapFour(state.two.three.four))
The issue arises when the compiler warns that state.two.three.four
inside mapFour
could be undefined due to limitations in type narrowing.
To address this, I need to explicitly declare a type guard annotation like so:
.filter((state):state is MyNewTypeWhereFourIsNotOptional => ...)
This is why I am seeking guidance on creating a new type with a specific deeply-nested property being required.