The code below throws me the ts error: Property 'id' does not exist on type '{ id: string } | undefined'.
because group is optional. In spite of that I want to get the type of id. How can i do that?
interface list{
group?: {
id: string;
}
}
const something: list["group"]["id"] = {} as any;
(Ignore the {} as any
, this is just an example)
CodePudding user response:
Typescript provides the Partial
and Required
helpers to make all properties of an object either optional or non optional.
You can read more about typescript utility types here.
So in your case you can use Required<list>
to turn group
into a non optional property:
interface list{
group?: {
id: string;
}
}
const something: Required<list>["group"]["id"] = "foo"