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

How to extract literal type from property value of a typed object?

type Animal = { name: string } // imported from 3rd party module


const cat: Animal = {
    name: 'Cat' as const,
}


const dog = {
    name: 'Dog' as const
}

type CatName = typeof cat.name // = string, not 'Cat' !!!
type DogName = typeof dog.name // = 'Dog'

In above code, how can I get a literal type CatName = 'Cat' (like DogName = 'Dog')?

Note: I can’t change the definition of type Animal because it’s 3rd party code, and I’d like to keep the value cat to be typed.

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 :

and I’d like to keep the value cat to be typed

If you explicitly type cat as Animal, then no, you can’t get 'Cat' out. You can type it more precisely const cat: { name: 'Cat' } (which is a subtype of Animal) or even const cat: Animal & { name: 'Cat' } if you want to be explicit it’s an Animal.

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