美文网首页
Extract Literal String Types fro

Extract Literal String Types fro

作者: forks1990 | 来源:发表于2018-10-04 11:29 被阅读0次

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

相关文章

网友评论

      本文标题:Extract Literal String Types fro

      本文链接:https://www.haomeiwen.com/subject/dzkxaftx.html