Ronni Egeriis Persson
Ronni Egeriis Persson

Reputation: 2289

Can enum be used to type an array

I am wondering if there is a way to use an enum to describe the valid types an array can contain. I have yet to find a way to make this happen, is it possible?

Here's the example I have attempted:

interface User {
    name: string;
}

interface Admin {
    level: number;
}

enum Person {
    User,
    Admin,
}

const persons: Person[] = [
    { name: 'hello' },
    { level: 1 },
];

Playground


Something similar is possible with a union, just to clarify what I'm trying to achieve:

interface User {
    name: string;
}

interface Admin {
    level: number;
}

type Person = User | Admin;

const persons: Person[] = [
    { name: 'hello' },
    { level: 1 },
];

Upvotes: 0

Views: 64

Answers (1)

Luke Storry
Luke Storry

Reputation: 6702

Enums can be used to define a set of named constants, and these can be used by Typescript as a type to limit a parameter to only the values of that enum.

If you want to define a set of possible types, like in your first code snippet, you should use unions, as you have done in your second code snippet.

https://www.typescriptlang.org/docs/handbook/enums.htm https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types

Upvotes: 1

Related Questions