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.
CodePudding user response:
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.
CodePudding user response:
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;
}
}