【问题标题】:Why are enums not enforced in typescript?为什么在打字稿中没有强制使用枚举?
【发布时间】:2021-08-10 03:23:51
【问题描述】:

我已将问题归结为几行代码。本质上,我正在接收一个对象并希望将其转换为接口。但是,在进行强制转换时不会强制执行枚举。这是一个简化的示例,显示未强制执行枚举。如何正确地将对象转换为接口?

enum Color {
  Blue,
  Green,
  Brown 
}

interface Person {
  eye: Color
}

const myObj: any = {
  eye: 'Orange'
};

const myPerson: Person = myObj;
console.log(myPerson.eye); // Prints 'Orange'

【问题讨论】:

  • 呃,不要用any
  • @Bergi 是对的。如果您只是将演员表移除到any,那么一切都会按您的预期进行。您的代码显示 Type 'string' is not assignable to type 'Color' 错误:tsplay.dev/Nal96w

标签: javascript typescript enums casting enumeration


【解决方案1】:

您可以使用Type而不是Interface来实现您想要实现的目标

type Color  = 'Blue' | 'Green' | 'Brown';

interface Person {
    eye: Color
}

const myObj: Person = { // Use the interface instead of any
    eye: 'Orange'
};

const myPerson: Person = myObj;
console.log(myPerson.eye); 

那么在使用指定颜色以外的其他颜色时会出现类型错误

采用Interface 方式,您将拥有数字映射,并且必须像本例中那样分配:

enum Color {
    Blue,
    Green,
    Brown
}

interface Person {
    eye: Color
}

const myObj: Person = {
    eye: Color.Blue // Here the value is 0 then
};

const myPerson: Person = myObj;
console.log(myPerson.eye); // Prints 0

【讨论】:

  • const myObj = { eye: 'Orange' }; 也有预期的效果,仍然实现了接口,同时提高了简洁性并增加了编译器拾取错误的几率
【解决方案2】:

这是因为any 输入了myObj

就像在 documentation 中一样,any “让 TypeScript 相信特定的代码行是可以的。”

【讨论】:

    【解决方案3】:

    Typescript 确实强制枚举作为类型。但是,您的示例不会产生预期的效果。通过暗示 myObjany 类型,没有强制执行任何类型。

    enum Status {
        ONLINE,
        OFFLINE,
        ERROR
    }
    
    status: Status = "Active";
    

    这将给出以下 Typescript 错误: TS2322: Type '"Active"' is not assignable to type 'Status'.

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 2020-10-27
      • 2017-02-03
      • 2019-03-04
      相关资源
      最近更新 更多