Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript – How to get the type of an optional nested prop in an interface

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;

TS Playground

(Ignore the {} as any, this is just an example)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"

Typescript Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading