Suppose we have a serial of shape types:
interface Rectangle {
type: 'rect';
w, h: number;
}
interface Circle {
type: 'circle';
x, y, r: number;
}
interface Triangle {
type: 'triangle';
p1, p2, p3: Point;
}
type Shape = Rectangle | Circle | Triangle;
How we get literal string types of type
field, i.e.:
type ShapeTypes = 'rect' | 'circle' | 'triangle';
Write by hand like upper is terrible if we got many shape types. Here is the solution:
function _shapeTypes(shape: Shape) {
return shape.type;
}
type ShapeTypes = ReturnType<typeof _shapeTypes>;
Now ShapeTypes
is 'rect' | 'circle' | 'triangle'
.
网友评论