gpt4 book ai didi

带参数的 typescript 枚举

转载 作者:搜寻专家 更新时间:2023-10-30 21:40:53 24 4
gpt4 key购买 nike

我想要严格类型化的可变对象,就像 Haxe 枚举一样。

In haxe, you can do

enum Color {
Red;
Rgb(r:Int, g:Int, b:Int);
Rgba(r:Int, g:Int, b:Int, a:Int);
}

我希望仅当我的对象是 Rgba 时才能访问 a 参数,如果我的对象是 a,我将无法访问任何参数红色

我真的不在乎我是否在 typescript 中使用 enum 关键字。

有什么方法可以在 Typescript 中实现吗?

最佳答案

从 2.0 版开始,Typescript supports tagged unions在某种程度上。一般语法是

type MyType = A | B | C …;

其中ABC是接口(interface)。 MyType 对象可以是这些类型中的任何一种,不能是其他类型。公告给出了一个简单的例子:

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;

function area(s: Shape) {
// In the following switch statement, the type of s is narrowed in each case clause
// according to the value of the discriminant property, thus allowing the other properties
// of that variant to be accessed without a type assertion.
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.width * s.height;
case "circle": return Math.PI * s.radius * s.radius;
}
}

但是,如示例所示(检查 s.kind),如果需要使用所谓的“判别属性类型保护”手动保护和检查这些联合类型的类型安全性。

关于带参数的 typescript 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40656955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com