Extract Literal String Types fro

2018-10-04  本文已影响0人  forks1990

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

上一篇 下一篇

猜你喜欢

热点阅读