Home > Back-end >  How to convert a string literal type to the keys of a new type?
How to convert a string literal type to the keys of a new type?

Time:11-30

Let's suppose I have a string literal type:

type Letters = "a" | "b" | "c" | "d" | "e";

How can I create the following type based on Letters?

type LetterFlags = {a: boolean, b: boolean, c: boolean, d: boolean, e: boolean};

I have tried

type Flags<T> = { [k in keyof T]: boolean };
type LetterFlags = Flags<Letters>;

but

const flags: LetterFlags = {a: true, b: false, c: true, d: false, e: true};

raises

Type '{ a: boolean; b: boolean; c: boolean; d: boolean; e: boolean; }' is not assignable to type '"e"'.

CodePudding user response:

You could do like this:

type Letters = "a" | "b" | "c" | "d" | "e";

type Flags<T extends string | number | symbol> = Record<T, boolean>;
type LetterFlags = Flags<Letters>;

const flags: LetterFlags = { a: true, b: false, c: true, d: false, e: true };

TypeScript playground

CodePudding user response:

This is based on @Guerric P's answer. I'm a Typescripe newb, wondering if this would also work (seems to)

enum Letter {
    a = "a",
    b = "b",
    c = "c",
    d = "d",
    e = "e",
}

type Flag = Record<Letter, boolean>;

const flag: Flag = {a: true, b: false, c: true, d: false, e: true};

Typescript Playground

  • Related