Home > Software design >  How to extract literal type from property value of a typed object?
How to extract literal type from property value of a typed object?

Time:05-30

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.

CodePudding user response:

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.

  • Related