简体   繁体   English

TypeScript 似乎希望我在枚举上断言一个类型,该枚举似乎已经在使用

[英]TypeScript seemingly wants me to assert a type on an enum, that the enum already seems to be using

I have an enum on an interface - where the value of the interface is always going to be a particular enum.我在一个接口上有一个枚举——接口的值总是一个特定的枚举。 In this case, a Monkey always has favouriteFruit set to Fruit.BANANA在这种情况下,猴子总是将favouriteFruit设置为Fruit.BANANA

declare enum Fruit{
    BANANA= "banana",
    APPLE = "apple",
}

export interface Monkey {
    ...
    favouriteFruit: Fruit.BANANA;
}

I have some data that needs to conform to that interface:我有一些需要符合该接口的数据:

  ...
  favouriteFruit: Fruit.BANANA
  ...

But typescript complains with:但是打字稿抱怨:

Type 'Fruit' is not assignable to type 'Fruit.BANANA'.

But if I do:但如果我这样做:

favouriteFruit: Fruit.BANANA as Fruit.BANANA

The error goes away.错误消失。

Why does TypeScript want to me assert the type on the enum?为什么 TypeScript 要我断言枚举上的类型?

You should not attempt to hardcode enum values, as enum values are specifically designed to hide away the underlying constant.您不应尝试对枚举值进行硬编码,因为枚举值专门设计用于隐藏底层常量。

Correct way to do this in case you don't need to assign a string literal but can use the enum would be:如果您不需要分配字符串文字但可以使用枚举,那么正确的方法是:

 enum Fruits {
      BANANA = 'banana',
        APPLE = 'apple',
          CHERRY = 'cherry'
   }

   interface Monkey {
         favoriteFruit: Fruits
   }

   interface SpecificMonkey extends Monkey {
         type: Fruits.BANANA
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM