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 make a type that is the keys of an interface but only the keys that are strings

Suppose I have this interface

interface MyInterface {
   val1: string
   val2: string
   val3: number
   val4: string
   val5: Date
}

I want to make a type that is the keys of the MyInterface but only the keys that are strings:

type myType = keyof MyInterface //where key === typeof 'string'
// myType: 'val1' | 'val2' | 'val4'

How could I do something like this?

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 :

You can use a mapped type to preserve only specif keys and then do a keyof on the resulting type

type myType = keyof {
    [P in keyof MyInterface as MyInterface[P] extends string ? P: never]: any
}

Playground Link

You could also make it generic


type KeyOfType<T, V> = keyof {
    [P in keyof T as T[P] extends V? P: never]: any
}

type myType = KeyOfType<MyInterface, string>
type myType2 = KeyOfType<MyInterface, number>

Playground Link

The as clause of a mapped type allows us to manipulate the name of the key. If the key is mapped to never the key gets removed from the resulting type. You can find more info in this PR

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