how to use typescript infer in typescript

TypeScript, Generics

TypeScript, Conditional Types

TypeScript, Type Operators

TypeScript, Advanced Types

To use infer in TypeScript, first, you need to understand conditional types.

Conditional types allow you to create a type that is dependent on another type, and which is chosen based on a condition that can be evaluated at compile-time.

The infer keyword is used to declare a type variable in a conditional type, which is then inferred based on the type of a type parameter or another type.

Here is an example of how to use infer in a conditional type:

index.ts
type InferType<T> = T extends { value: infer U } ? U : never;

type Test = { value: string };

type Result = InferType<Test>; // Result is inferred as string
158 chars
6 lines

In this example, the InferType type takes a type T as its parameter, and then checks if T has a property called value.

If T has a property called value, the infer keyword is used to declare a type variable U, which is inferred to be the type of the value property.

Finally, the InferType type returns U, the inferred type of value.

So, when we use the InferType type with Test as its parameter, we get string as the inferred type.

This is just one example of how infer can be used in a conditional type. With this feature, you can write more generic and reusable code, and leverage the power of the TypeScript type system.

related categories

gistlibby LogSnag