Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript template literal for object key mapping

I’m trying to create a generic type that would map the keys using template literals. In general i just want all the keys listed in the generic type to be present in the output type, but modified slightly. Something along the lines of:

type TFoobar = "foo" | "bar";

const foobar: TFlagDict<TFoobar> = {
    "foo_flag": true,
    "bar_flag": true
};

I have tried implementing it like so:

type TFlagDict<TProperties extends string> = {
    [key in TProperties]: {[k in `${key}_flag`]: boolean}
}[TProperties]

And while it does have a proper typing, it makes the properties optional (at least one is required, but there is nothing that enforces they are all present)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const foo: TFlagDict<TFoobar> = {
    "foo_flag": true
}; //valid, shouldnt be

const bar: TFlagDict<TFoobar> = {
    "bar_flag": true
}; //valid, shouldnt be

const foobar: TFlagDict<TFoobar> = {
    "foo_flag": true,
    "bar_flag": true
}; //valid

>Solution :

You were close:

type TFoobar = "foo" | "bar";

const foobar: TFlagDict<TFoobar> = {
    "foo_flag": true,
    "bar_flag": true
};

type TFlagDict<TProperties extends string> = {
    [key in TProperties as `${key}_flag`]: boolean // key remapping
}

type O = TFlagDict<TFoobar>
const foo: TFlagDict<TFoobar> = {
    "foo_flag": true
}; //error

const bar: TFlagDict<TFoobar> = {
    "bar_flag": true
}; //error

const foobar2: TFlagDict<TFoobar> = {
    "foo_flag": true,
    "bar_flag": true
}; //valid

Playground

You are allowed to use as inside iterator. See docs for more context

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading