[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,
};
};
相关文章
- [Typescript] Use never for readable string
- [Typescript] Extract the Result From Several Possible Function Shapes
- [Typescript] Create an Object Whose Keys Are Derived From a Union
- [Typescript] Function scope in typescript
- [Typescript] Get a TypeScript package ready for release to NPM
- [Typescript] Tips: Map over a union type
- [Typescript + React] Tips: Write your own 'PropsFrom' helper to extract props from any React component
- [Typescript] Narrow the unknown Type with TypeScript's Assertion Functions
- [Typescript] Statically Type Unknown Values with TypeScript's unknown Type
- [Typescript] Create Type From Any Given Data in TypeScript
- [Typescript] Make your optional fields required in TypeScript
- [TypeScript] Export public types from your library
- [Typescript] Make TypeScript Class Usage Safer with Strict Property Initialization
- [VueJS + Typescript] Decouple Dependencies Using IoC Containers in Vue with TypeScript and InversifyJS
- [Typescript] Sorting arrays in TypeScript
- [Typescript] Default value for Builder pattern - 04 (keyof {} -> never)
- [Typescript 4.9] TypeScript 4.9: satisfies operator
- [Typescript] Extract the Result From Several Possible Function Shapes
- [Typescript] Remove one element from unit type
- [Typescript] Prevent Type Widening of Object Literals with TypeScript's const Assertions
- [Typescript] Statically Type Unknown Values with TypeScript's unknown Type
- [Typescript] Use the Optional Chaining Operator in TypeScript
- [Typescript] Ignore Null or Undefined Values with TypeScript Non-Null Assertion Operator
- [Typescript] Extend Functionality of a TypeScript Class with Decorators
- [Typescript] Emitting Declaration Files
- [TypeScript] Type check JavaScript files using JSDoc and Typescript 2.5
- typescript ts参数展开运算符:形参展开和实参展开及as const的用法示例
- TypeScript Decorators 的使用说明
- TypeScript 类装饰器的一个例子和使用单步调试搞清楚其运行原理