简体   繁体   English

打字稿:在接口中使用枚举值

[英]typescript: using enum values in interfaces

I have an interface that uses an enum value in one of its fields: 我有一个在其字段之一中使用枚举值的接口:

export enum AnimalType {
    DOG,
    CAT,
}


export interface DogAttrs {
    bones: boolean,
    type: AnimalType.DOG
}

and my goal is a function that creates dogs and adds them to the list of dogs. 我的目标是创建狗并将其添加到狗列表的功能。

function addDog(animalList: DogAttrs[]) {
    const animal = {
        type: AnimalType.DOG,
        bones: true
    }
    animalList.push(animal);   
}

but this function says the object I create is wrong and it does not conform to the DogAttrs interface: 但是此函数表示我创建的对象是错误的,并且不符合DogAttrs接口:

Type 'AnimalType' is not assignable to type '"DOG"'.

why is that? 这是为什么? and how to fix this? 以及如何解决这个问题?

live example: 现场示例:

https://www.typescriptlang.org/play/#code/FAUwHgDg9gTgLgAhAOwK4FsEEFkEt0CGANgCoCeEICA3sAvQgCIDyA4ggLwIDkLr3AGjoMAwlhKceYkoOABfYIvDR4CXMjggYAMwIBjKoygBzLHDgwAzjWH0ARlGQhLALgQOoREAWRCGCOAoQN142bnlFRW1UZD04XEcEAgATZKNjAAoffGIAGVxLODd0swtLAG0AXQBKG389R0KkvEIiSVp-f0DKNxwc0iCAOj4-TvtHZzcLVBBbBAV-bNb8wsGIVEsACyyW4mqAbgYIyOAgA https://www.typescriptlang.org/play/#code/FAUwHgDg9gTgLgAhAOwK4FsEEFkEt0CGANgCoCeEICA3sAvQgCIDyA4ggLwIDkLr3AGjoMAwlhKceYkoOABfYIvDR4CXMjggYAMwIBjKoygBzLHDgwAzjWH0ARlGQhLALgQOoREAWRCGCOAoQN142bnlFRW1UZD04XEcEAgATZKNjAAoffGIAGVxLODd0swtLAG0AXQBKG389R0KkvEIiSVp-f0DKNxwc0iCAOj4-TvtHZzcLVBBbBAV-bNb8wsGIVEsACyyW4mqAbgYIyOAgA

The problem is that typescript will widen the type of the constant when you assign them to the variable. 问题在于,当您将打字稿分配给变量时,打字稿会扩大常量的类型。 The simple solution is to use an as const assertion or to specify the type of the constant explicitly: 简单的解决方案是使用as const断言或显式指定as const的类型:

function addDog(animalList: DogAttrs[]) {
    const animal: DogAttrs = {
        type: AnimalType.DOG,
        bones: true
    }
    animalList.push(animal);   
}

Or 要么

function addDog(animalList: DogAttrs[]) {
    const animal = {
        type: AnimalType.DOG,
        bones: true
    } as const
    animalList.push(animal);   
}

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

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