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

Get the type of a property of an Union Type in typescript

Suppose we have some interfaces with a name property (and possibly others):

interface Circle {
   name: 'circle',
   radius: number
}

interface Sphere {
   name: 'sphere',
   radius: number
}

interface Square {
   name: 'square',
   side: number
}

type GeometricalObject = Circle | Sphere | Square;

Now, suppose we have a function:

   doSomething(name: SomeType) {
     ...     
   }

Is there a way to assure that the name argument’s type of doSomething() function is the union of the name property possible types in GeometricalObject (i.e. ‘circle’ | ‘sphere’ | ‘square’, in this specific case) programmatically?

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

I was imagining something like typeof GeometricalObject.name, if that was possible.

>Solution :

interface Circle {
   name: 'circle',
   radius: number
}

interface Sphere {
   name: 'sphere',
   radius: number
}

interface Square {
   name: 'square',
   side: number
}

type GeometricalObject = Circle | Sphere | Square;

type Name = GeometricalObject["name"]; // "circle" | "sphere" | "square"

It is possible; it’s using bracket notation instead of dot notation.

Playground

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