Create object with template literal types and generic

Viewed 135

I try to create an Object with the new Typescript 4.1 literal types feature. But if generic come into place, everything breaks. What I'm missing?

export type MyType<T extends string> = {
  propFromMyType: T;
};

export type TypeWithGenericLiteral<T extends string> = {
  [P in `${T}_with_literal`]: number;
};

// works fine
export const create1 = (t: MyType<"example">): TypeWithGenericLiteral<"example"> => {
    const prop = `${t.propFromMyType}_with_literal` as const;

    return {
        [prop]: 777
    };
}

// does not work
export const create2 = <T extends "example"> (t: MyType<T>): TypeWithGenericLiteral<T> => {
    const prop = `${t.propFromMyType}_with_literal` as const;

    return {
        [prop]: 777
    };
} 


// does not work
export const create3 = <T extends string> (t: MyType<T>): TypeWithGenericLiteral2<T> => {
    const prop = `${t.propFromMyType}_with_literal` as const;

    return {
        [prop]: 777
    };
} 

link to typescript playground

0 Answers
Related