[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,
  };
};

 

posted @ 2023-04-10 21:31  Zhentiw  阅读(11)  评论(0编辑  收藏  举报