Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array of strings to typescript types?

I've this array:

const arr = ["foo", "bar", "loo"]

I need to convert it to a typescript type

type arrTyp = "foo" | "bar" | "loo";

How can I do this in typescript?

like image 555
Wajahath Avatar asked Jan 07 '19 08:01

Wajahath


People also ask

Should I use [] or array in TypeScript?

There is no difference at all. Type[] is the shorthand syntax for an array of Type . Array<Type> is the generic syntax. They are completely equivalent.

How do I cast an array in TypeScript?

There are 4 possible conversion methods in TypeScript for arrays: let x = []; //any[] let y1 = x as number[]; let z1 = x as Array<number>; let y2 = <number[]>x; let z2 = <Array<number>>x; The as operator's mostly designed for *. tsx files to avoid the syntax ambiguity.

How do you define a type of array in TypeScript?

An array in TypeScript can contain elements of different data types using a generic array type syntax, as shown below. let values: (string | number)[] = ['Apple', 2, 'Orange', 3, 4, 'Banana']; // or let values: Array<string | number> = ['Apple', 2, 'Orange', 3, 4, 'Banana'];


1 Answers

Edit for 3.4 and higher:

In 3.4 const assertions were added, so we can get a string literal type tuple using as const:

const arr = ["foo", "bar", "loo"] as const

type arrTyp = typeof arr[number]; // "foo" | "bar" | "loo"

Original

The problem is that arr does not preserve the literal types in the array, it will be infered to string[]. If you use a function to force the inference of string literal type, extracting the type is a simple affair:

function tuple<T extends string[]>(...o: T) {
    return o;
}
const arr = tuple("foo", "bar", "loo")

type arrTyp = typeof arr[number]; // "foo" | "bar" | "loo"

The function forces the compiler to infer a tuple of string literals for arr. So arr will be typed as ["foo", "bar", "loo"]. We can then use a type query to get a union of the elements in the tuple. You can read more about type queries here

like image 157
Titian Cernicova-Dragomir Avatar answered Nov 15 '22 18:11

Titian Cernicova-Dragomir