const names = ['jacob', 'master jung', 'kyuhyun'] as const;
type Names = typeof names[number];
I got the results I wanted, but I don't understand typeof names[number]
.
What does typeof Array[number]
in Typescript mean?
An array in TypeScript can contain elements of different data types using a generic array type syntax, as shown below. Example: Multi Type Array. let values: (string | number)[] = ['Apple', 2, 'Orange', 3, 4, 'Banana']; // or let values: Array<string | number> = ['Apple', 2, 'Orange', 3, 4, 'Banana'];
typeof is used to differentiate between the different types in TypeScript. By the use of typeof we can differentiate between number, string, symbol, Boolean, etc. typeof can be used with any type in TypeScript, by the use of it we can re-use the code by passing any parameter type.
The typeof operator returns "object" for objects, arrays, and null.
In TypeScript, an array is an ordered list of values. An array can store a mixed type of values. To declare an array of a specific type, you use the let arr: type[] syntax.
There is a comment made by the user @jcalz that explains how it works. It refers to the following code, which is similar to the OP code:
const fruit = ["apple", "banana", "grape"] as const;
export type Fruit = (typeof fruit)[number]; 'apple'|'banana'|'grape';
typeof fruit
isArray<"apple" | "banana" | "grape">
, soFruit
is equivalent to(Array<"apple" | "banana" | "grape">)[number]
. The syntaxT[K]
means: the type of the properties ofT
whose keys are of typeK
. So(Array<"apple" | "banana" | "grape">)[number]
means "the types of the properties ofArray<"apple" | "banana" | "grape">
whose keys are of typenumber
", or: "the array elements ofArray<"apple" | "banana" | "grape">
, or:"apple" | "banana" | "grape"
.
And another similar comment by that user that adds a bit more technical terms:
The type
T[K]
is a lookup type which gets the type of the property ofT
whose key isK
. In(typeof list)[number]
, you're getting the types of the properties of(typeof list)
whose keys arenumber
. Arrays liketypeof list
have numeric index signatures, so theirnumber
key yields the union of all numerically-indexed properties.
typeof
gets the type of names
variable (which is readonly ['jacob', 'master jung', 'kyuhyun']
) then array/tuple member type is resolved. This is called indexed access types or lookup types.
Syntactically, they look exactly like an element access, but are written as types
In this case we "query" the type of tuple member (tuple/array at index) which is 'jacob' | 'master jung' | 'kyuhyun'
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With