How to create a Union type from the elements of an array type in Typescript?

Asked

Viewed 53 times

1

I have this code:

const array = [1, 2, 3, 4, 5]

interface data ...

How do I get the contents of array and kind on date? As if it were so:

interface data {
    numbers: 1 | 2 | 3 | 4 | 5
}

PS: I nay I want to type the array, I want to type the contents of the array, I mean, I don’t want it:

interface data {
    numbers: number[]
}
  • interface data{
 numbers: int[];
} That’s what you want to know?

  • @Ricardopontual Não

  • @Ricardopunctual I want it to take the array values and use as type

  • but what kind? isn’t an array of integers? would that be int[], or you want to turn the array into a string separates by pipe (|) ?

  • @Ricardopunctual I want to take the array elements and type them, not the array itself

  • not to do this in an interface... the array should already be of a certain type, as int or string, if you do not know what will come in the array only power object , then on the interface should be any[], and who will type has to be the implementation, the class

  • @Ricardopunctual, actually, it does! :-) Behold.

Show 2 more comments

1 answer

2


You can get a union with all array types using bracket notation. So:

type MyArr = [1, 2, 3, 4, 5];

// %inferred-type: 5 | 1 | 2 | 3 | 4
type MyArrUnion = MyArr[number];

See on Typescript playground.

Note that in this case the type of the array is static. If you need to get the type from an existing array, use the operator typeof (in the context of static typing). Example:

const myArr = [1, 2, 3, 4, 5] as const; // Note que a asserção `as const` foi necessária para preservar o tipo estático que colocamos.

type MyArr = typeof myArr;

// %inferred-type: 1 | 2 | 3 | 4 | 5
type MyArrUnion = MyArr[number];

See on Typescript playground.

What if the inferred type of MyArr was something like number[], MyArr[number] would also work, only that would be inferred the type number.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.