小编acr*_*stu的帖子

打字稿只读对象文字

我有一个复杂的数据模型,我需要在其中定义 40-50 个单例“元数据”对象:

  • 使用歧视联合
  • 有一些常规字段,但也有一个字典,它可以包含任意数量的属于歧视联盟的对象

我希望能够保留为对象文字创建的隐式类型,以便我可以使用智能感知以类型安全的方式操作这 40-50 个对象。

这是一个使用高级类型打字稿文档中的形状的示例:

interface Square {
    kind: "square";
    size: number;
}
interface Rectangle {
    kind: "rectangle";
    width: number;
    height: number;
}
interface Circle {
    kind: "circle";
    radius: number;
}
type Shape = Square | Rectangle | Circle;
type Shapes = { [x: string]: Shape };

interface Canvas { 
    name: string;
    size: number;
    //etc
}
interface Drawing extends Canvas {
    shapes: Shapes;
}

//compiles but does not give me intellisense on drawingExplicitType.shapes because …
Run Code Online (Sandbox Code Playgroud)

typescript

5
推荐指数
1
解决办法
2493
查看次数

标签 统计

typescript ×1