带参数的 typescript 枚举

标签 typescript types

我想要严格类型化的可变对象,就像 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 参数,如果我的对象是红色

我并不关心在 typescript 中是否使用enum关键字。

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

最佳答案

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

type MyType = A | B | C …;

哪里A , BC是接口(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/

相关文章:

javascript - Typescript 过滤并返回单个键

node.js - NestJS 条件模块导入

javascript - 将 GraphQL 错误存储为字符串

TypeScript 类型忽略大小写

types - 使用JwtSessionHandler时键入错误-dart

c - 类型 `rune_t`在C中代表什么?

typescript - 预期有 0​​ 个类型参数,但得到了 1 个

javascript - 如何在 TypeScript 中使用声明文件

haskell - 具有 Haskell 函数依赖性的不明确类型变量

c++ - Qt QMetaObjects 和从 QWidget 到 QObject 的转换