davimdantas
davimdantas

Reputation: 143

Force value verification with Numeric Enum

Shouldn't I receive a warning for this:

enum Animals {
    CAT = 1, DOG, SNAKE
}


interface AnimalsTest {
    animalKind: Animals.CAT | Animals.DOG | Animals.SNAKE
}

let myAnimal: AnimalsTest = {animalKind: 4};

I expect to restrict a property number with this kind of logic, but it's not working. Could I change it and use enums for this purpose?

Upvotes: 0

Views: 32

Answers (1)

georg
georg

Reputation: 214959

number is assignable to enum (see https://github.com/microsoft/TypeScript/issues/26362) and there's no way to create a type from enum values. If you need this functionality, an object with a const assertion would be a better option:

const Animals = <const>{
    CAT: 1,
    DOG: 2
}

type Values<T> = T[keyof T]

interface AnimalsTest {
    animalKind: Values<typeof Animals>
}

let a: AnimalsTest = {animalKind: Animals.DOG}; // ok
let b: AnimalsTest = {animalKind: 2}; // ok too
let c: AnimalsTest = {animalKind: 42}; // not ok

Upvotes: 1

Related Questions