简体   繁体   中英

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

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?

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
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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