முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 6 · பாடம் 1 இன் 2பாடத்திட்டத்தில் 11/14~15 min
தொகுதி பாடங்கள் (1/2)

நிபந்தனை வகைகள் மற்றும் அனுமானம்

Conditional types allow you to express non-trivial type decisions based on inheritance relationships. The syntax resembles JavaScript's ternary operator:

TS
T extends U ? X : Y

If type T is assignable to U, then the resulting type will be X, otherwise it will be Y.


Basic Conditional Types

A conditional type evaluates a condition at compile time:

TS
type IsNumber<T> = T extends number ? true : false;

type A = IsNumber<number>; // true
type B = IsNumber<string>; // false

This pattern is extremely powerful when combined with generics to create flexible and dynamic utility types.


Type Extraction with infer

Inside the extends clause of a conditional type, we can use the infer keyword to declare a type variable to be inferred by the compiler.

For example, if we want to extract the return type of a function:

TS
type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

type ExampleFunction = () => string;
type Return = GetReturnType<ExampleFunction>; // string

In this example, infer R tells TypeScript to automatically determine the function's return type and make it available as R in the positive branch of the conditional.


Try it yourself

Exercise 1: The IsString Type

உடற்பயிற்சி#ts.m6.l1.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Create a generic type named IsString<T> that returns the literal type true if T extends string, otherwise false.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Use the syntax type IsString<T> = T extends string ? true : false; to check the type.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Exercise 2: Extracting a type from an Array with infer

உடற்பயிற்சி#ts.m6.l1.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Define a generic type UnpackArray<T> that uses infer to extract the element type of an array T. If T is an array (for example U[]), return U, otherwise return the same type T.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Use T extends (infer U)[] ? U : T to declare and return the inferred type variable U.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்