Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript literal types used as key to indexer

Tags:

typescript

Is there any way to define a typescript literal type which can be used as a string key in an indexer?

type TColorKey = 'dark' | 'light';

interface ColorMap {
    [period: TColorKey]: Color;
}

This throws the error: An index signature parameter type must be 'string' or 'number'.

like image 635
parliament Avatar asked Nov 21 '16 17:11

parliament


1 Answers

Yes, it is possible thanks to a new feature called Mapped types. Just make sure you're using nightly version of typescript compiler (typescript@next) because it's not in stable build yet (at the time I'm writing this).

type TColorKey = "dark" | "light";

type TColorMap = { [P in TColorKey]: Color };
like image 68
Erik Cupal Avatar answered Oct 24 '22 05:10

Erik Cupal