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 :
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.