Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript how to extract nested type

Tags:

typescript

How do I extract the type of a nested property? For example say I have this type:

type Example = {
   nested: string,  // how do I infer string here
   other: string
}

Such that I can extract out 'string' from Example.nested?

I have type myType = Pick<Example, "nested"> and that provides { nested: string }, but I want to infer the type of the property 'nested' (string, in this example) on that object.

like image 858
Michael Wilson Avatar asked Jun 26 '19 18:06

Michael Wilson


1 Answers

You want to use a lookup type (also called an "indexed access type") which uses the square bracket syntax.

That is,

type myType = Example["nested"] // string

Hope that helps; good luck!

Link to code

like image 129
jcalz Avatar answered Nov 16 '22 02:11

jcalz