'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?
I was imagining something like typeof GeometricalObject.name, if that was possible.
Solution 1:[1]
you can do something like this
interface Circle {
name: 'circle',
radius: number
}
interface Sphere {
name: 'sphere',
radius: number
}
interface Square {
name: 'square',
side: number
}
type GeometricalObject = Circle | Sphere | Square;
type GeometricalObjectType = Circle['name'] | Sphere['name'] | Square['name'];
function doSomething(name: GeometricalObjectType) {
switch(name) {
case 'circle':
break;
case 'sphere':
break;
case 'square':
break;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tiep Phan |
