How to get parts of an typescript interface
Martin Anders
Posted on October 5, 2020
Today i wanted to extract a part of an already existing complex typescript type or interface.
It's very difficult to google something when you don't know what to search for. This post will help you if you have one of these questions:
- How to get a nested type?
- How to get parts of an interface?
- How to get type of array elements?
- How to extract optional properties of a type?
I searched for this by myself and was not happy with the results.
So let's start
Let's say we have this type:
type Person = {
name: string
age: number
// nested object
address: {
street: string
}
// nested array
tags: string[]
// optional object
info?: {
eyeColor: string
}
}
Extract basic parts
To extract specific parts of this type we can use lookup types
type Name = Person["name"]
type Age = Person["age"]
type Address = Person["address"]
// deeply nested access is also possible
type Street = Person["address"]["street"]
Extract type of array elements
To get the type of an typed array like tags
we can use the lookup type for arrays:
type Tag = Person["tags"][0]
Optional properties
But how get the type of optional properties like info
correctly? Let's say we want the type of eyeColor
. To get base type of optional types properties correctly we have to use NunNullable type
type Info = NonNullable<Person["info"]>
type EyeColor = Info["eyeColor"] // string
Get type from Array values
const languages = ['de', 'en', 'fr', 'it'] as const;
// extract type from languages above
export type Language = typeof languages[number]; // same as de" | "en" | "fr" | "it"
Final thoughts
Another day for me with more typescript enlightenment ๐. Hope this post can help you as well.
Posted on October 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.