How to get parts of an typescript interface

madflanderz

Martin Anders

Posted on October 5, 2020

How to get parts of an typescript interface

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Final thoughts

Another day for me with more typescript enlightenment ๐Ÿ˜†. Hope this post can help you as well.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
madflanderz
Martin Anders

Posted on October 5, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About