[Typescript] Inferring Literal Types from any Basic Type
export const inferItemLiteral = <T>(t: T) => {
return {
output: t,
};
};
const result1 = inferItemLiteral("a");
// ? {output: string}
/* vs */
export const inferItemLiteral = <T extends string>(t: T) => {
return {
output: t,
};
};
const result1 = inferItemLiteral("a");
// ? {output: "a"}
So , what about if function can accpet number as input:
const result2 = inferItemLiteral(123);
We can do:
export const inferItemLiteral = <T extends string | number>(t: T) => {
return {
output: t,
};
};