Ich wollte einen Type haben, der aus values aus Objekten innerhalb von einem Array besteht.

const people = [
    {name : 'Kendrick', lastName: 'Lamar'},
    {name: 'Amy', lastName: 'Winehouse'},
];

type LastNameType = 'Lamar' | 'Winehouse';

const lastName : LastNameType = '';

Diesen LastNameType will ich natürlich nicht selbst schreiben. Die values des Array können sich ja irgendwann mal verändern.

Ich hätte gern so was gehabt:

type LastNameType = typeof people[number]['lastName'];

Aber der type des arrays people ist {name: string, lastName: string}. Dementsprechend ist typeof people[number]['lastName']string .

Die (schwer zu findende, aber geile) Lösung: as const um ein readonly Array zu erstellen 💥




Merkzettel für Typen im Bezug zu const:

let fooBar2 = 'abc'; // => type string
const fooBar1 = 'abc'; // => type 'abc'
let fooBar3 = ['abc']; // => type string[]
const fooBar4 = ['abc']; // => type string[]
const fooBar5 = ['abc'] as const; // => type ['abc']