zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] Inferring Literal Types from any Basic Type

typescript from type Basic any types literal
2023-09-14 08:59:11 时间
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,
  };
};