My goal is to create an Object using string literals.
export type MyCustomType<T extends string> = {
propertyFromCustomType: T;
};
export type CustomTypeWithLiteral<T extends string> = {
[P in `${T}_with_literal`]: number;
};
When my creation function does not involve a generic type, everything works smoothly:
const create = (t: MyCustomType<"example">): CustomTypeWithLiteral<"example"> => {
const prop = `${t.propertyFromCustomType}_with_literal` as const;
return {
[prop]: 777
};
}
However, when the creation function includes a type T itself, it encounters issues:
const create = <T extends string> (t: MyCustomType<T>): CustomTypeWithLiteral<T> => {
const prop = `${t.propertyFromCustomType}_with_literal` as const;
return {
[prop]: 777
};
}
Even specifying a specific literal type T does not resolve the problem:
type action = "example"
export type MyCustomType<T extends action> = {
propertyFromCustomType: T;
};
export type CustomTypeWithLiteral<T extends action> = {
[P in `${T}_with_literal`]: number;
};
const create = <T extends action> (t: MyCustomType<T>): CustomTypeWithLiteral<T> => {
const prop = `${t.propertyFromCustomType}_with_literal` as const;
return {
[prop]: 777
};
}