Table of Contents
1. Syntax and basic principles of conditional types
2. Distributed Conditional Types
3. Type filtering and extraction tools
Extract function type
Exclude certain types (similar to Exclude )
Extract certain types (similar to Extract )
Filter null/undefined (similar to NonNullable )
4. infer : Infer type in conditional type
Extract function return value type (similar to ReturnType )
Extract array element type (similar to ElementType )
Extract the parsed value of the Promise (similar to Awaited )
5. Practical Advanced Mode
1. DeepReadonly
2. Function overload parsing (simplified signature)
3. Joint transfer cross type (advanced skills)
6. Common traps and precautions
Summarize
Home Web Front-end JS Tutorial Advanced Conditional Types in TypeScript

Advanced Conditional Types in TypeScript

Aug 04, 2025 am 06:32 AM
java programming

TypeScript's advanced condition types implement logical judgment between types through the T extends U? X: Y syntax. Its core capabilities are reflected in the distributed condition types, infer type inference and the construction of complex type tools. 1. The conditional type is distributed in the bare type parameters and can automatically split the joint type, such as ToArray to obtain string[] | number[]. 2. Use distribution to build filtering and extraction tools: Exclude Exclude types through T extends U ? never : T, Extract Extract commonalities through T extends U ? T : never Extract commonalities, NonNullable filter null/undefined. 3. The infer keyword is used to match patterns in condition types and extract subtypes, such as ReturnType to extract the function return value, ElementType to obtain the array element type, and UnwrapPromise to unpack Promise content. 4. Advanced modes include DeepReadonly to implement object deep read-only, FirstParam to extract function parameter types, UnionToIntersection to convert union types to cross types to merge object structures. 5. Note that never is automatically ignored in union types, lazy evaluation behavior of conditional types, and conservative derivation results caused by any. Mastering these mechanisms can implement type-level logical operations, build safe and efficient generic abstractions, and ultimately improve the expression power and code reliability of the type system.

Advanced Conditional Types in TypeScript

Advanced Conditional Types of TypeScript are one of the most powerful and flexible parts of the type system. They allow you to dynamically generate new types based on relationships between types, and are often used to build complex type tools, type guards, and generic abstractions. Understanding these features will allow you to write safer and smarter type code.

Advanced Conditional Types in TypeScript

Here are some key concepts and practical tips that will take you into the deep understanding of advanced condition types.


1. Syntax and basic principles of conditional types

The syntax of conditional types is similar to that of JavaScript's ternary operators:

Advanced Conditional Types in TypeScript
 T extends U ? X : Y

Meaning: If type T can be assigned to U , then the result type is X , otherwise it is Y

example:

Advanced Conditional Types in TypeScript
 type IsString<T> = T extends string ? true : false;

type A = IsString<&#39;hello&#39;>; // true
type B = IsString<42>; // false

This seems simple, but its true power is reflected in combination with generics, union types, and distributed conditional types.


2. Distributed Conditional Types

When the conditional type acts on a generic and the generic appears to the left extends , TypeScript will automatically "distribute" the union type.

 type ToArray<T> = T extends any ? T[] : never;

If you pass string | number , TypeScript will disassemble it:

 ToArray<string | number> 
// Equivalent to:
// (string extends any ? string[] : never) | (number extends any ? number[] : never)
// The result is: string[] | number[]

✅ This "automatic distribution" only occurs on naked type parameters. If you wrap T in a tuple or object, such as [T] extends [any] , the distribution will be closed.

Purpose: Commonly used to process each item in a joint type separately, such as the extraction/filter type.


3. Type filtering and extraction tools

With distributed conditional types, we can build powerful type tools.

Extract function type

 type GetFunction<T> = T extends (...args: any[]) => any ? T : never;

type FuncsOnly = GetFunction<string | () => number | number | (s: string) => void>;
// Result: () => number | (s: string) => void

Exclude certain types (similar to Exclude )

 type Exclude<T, U> = T extends U ? never : T;

type NoString = Exclude<string | number | boolean, string>; // number | boolean

This is how TypeScript's built-in Exclude<T, U> is implemented.

Extract certain types (similar to Extract )

 type Extract<T, U> = T extends U ? T : never;

type OnlyStringOrNumber = Extract<string | number | boolean, string | number>; // string | number

Filter null/undefined (similar to NonNullable )

 type NonNullable<T> = T extends null | undefined ? never : T;

type A = NonNullable<string | null | undefined>; // string

4. infer : Infer type in conditional type

infer is a weapon for "pattern matching" and extracting subtypes in conditional types.

Extract function return value type (similar to ReturnType )

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

type R = ReturnType<() => string>; // string

Extract array element type (similar to ElementType )

 type ElementType<T> = T extends (infer U)[] ? U : never;

type Item = ElementType<number[]>; // number
type Item2 = ElementType<string[]>; // string

Extract the parsed value of the Promise (similar to Awaited )

 type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;

type Value = UnwrapPromise<Promise<string>>; // string
type Value2 = UnwrapPromise<number>; // number

infer can appear in tuples, function parameters, return values, object properties, etc., to realize complex type deconstruction.


5. Practical Advanced Mode

1. DeepReadonly

 type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object 
    ? T[K] extends Function 
      ? T[K] 
      : DeepReadonly<T[K]> 
    : T[K];
};

Here we use the condition type to determine whether the field is an object and avoid recursion of the function.

2. Function overload parsing (simplified signature)

 type FirstParam<F> = F extends (arg: infer P) => any ? P : never;

type ID = FirstParam<(id: string) => void>; // string

3. Joint transfer cross type (advanced skills)

Sometimes you want to convert string | number to string & number (although the result is never ), but it is more common to use "inverter" processing for function parameters.

 type UnionToIntersection<U> = 
  (U extends any ? (k: U) => void : never) extends (k: infer I) => void 
    ? I 
    : never;

type T = UnionToIntersection<{a:1} | {b:2}>; // {a:1} & {b:2}

This technique is often used to "merge" multiple types in type derivation.


6. Common traps and precautions

  • never will be ignored in union type

     type T = string | never; // equivalent to string

    Therefore, it is effective to use never to "filter out" the type in Exclude .

  • Condition types are lazy

    Conditional types are calculated only when instantiated. For example:

     type Foo<T> = T extends string ? string : number;
    type A = Foo<any>; // type is string | number

    Because any and string are "fuzzy", TypeScript will conservatively return string | number .

  • Never's special behavior

    never is a subtype of all types, so in the conditional type:

     type T = never extends string ? true : false; // true

    But this does not mean that never is a string, but that is the type system rules.


    Summarize

    Advanced conditional types are at the heart of TypeScript type programming. Combining extends , infer and distributed behavior, you can:

    • Filter, extract, convert types
    • Implement type-level "logical judgment"
    • Build complex generic tools (such as Pick , Omit , ReturnType , etc.)

    Although it seems like magic at the beginning, as long as you understand the idea of "type is a set" and "conditional type is a set judgment", you can gradually master it.

    Basically that's it. Write more and try more, and you will find that the type system is more powerful than you think.

    The above is the detailed content of Advanced Conditional Types in TypeScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1592
276
Using XSLT Parameters to Create Dynamic Transformations Using XSLT Parameters to Create Dynamic Transformations Aug 17, 2025 am 09:16 AM

XSLT parameters are a key mechanism for dynamic conversion through external passing values. 1. Use declared parameters and set default values; 2. Pass the actual value from application code (such as C#) through interfaces such as XsltArgumentList; 3. Control conditional processing, localization, data filtering or output format through $paramName reference parameters in the template; 4. Best practices include using meaningful names, providing default values, grouping related parameters, and performing value verification. The rational use of parameters can make XSLT style sheets highly reusable and maintainable, and the same style sheets can produce diversified output results based on different inputs.

You are not currently using a display attached to an NVIDIA GPU [Fixed] You are not currently using a display attached to an NVIDIA GPU [Fixed] Aug 19, 2025 am 12:12 AM

Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

How to use Optional in Java? How to use Optional in Java? Aug 22, 2025 am 10:27 AM

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

Exploring Common Java Design Patterns with Examples Exploring Common Java Design Patterns with Examples Aug 17, 2025 am 11:54 AM

The Java design pattern is a reusable solution to common software design problems. 1. The Singleton mode ensures that there is only one instance of a class, which is suitable for database connection pooling or configuration management; 2. The Factory mode decouples object creation, and objects such as payment methods are generated through factory classes; 3. The Observer mode automatically notifies dependent objects, suitable for event-driven systems such as weather updates; 4. The dynamic switching algorithm of Strategy mode such as sorting strategies improves code flexibility. These patterns improve code maintainability and scalability but should avoid overuse.

Operating System not found [Fixed] Operating System not found [Fixed] Aug 17, 2025 am 09:10 AM

Ifyourcomputershows"OperatingSystemnotfound,"trythesesteps:1.CheckBIOS/UEFIbootorder.2.Verifydiskconnections.3.RepairbootloaderusingWindowsRecovery.4.ReassigndriveletterviaDiskManagement.5.Reinstalltheoperatingsystemifnecessary.

PS oil paint filter greyed out fix PS oil paint filter greyed out fix Aug 18, 2025 am 01:25 AM

TheOilPaintfilterinPhotoshopisgreyedoutusuallybecauseofincompatibledocumentmodeorlayertype;ensureyou'reusingPhotoshopCS6orlaterinthefulldesktopversion,confirmtheimageisin8-bitperchannelandRGBcolormodebycheckingImage>Mode,andmakesureapixel-basedlay

Building Cloud-Native Java Applications with Micronaut Building Cloud-Native Java Applications with Micronaut Aug 20, 2025 am 01:53 AM

Micronautisidealforbuildingcloud-nativeJavaapplicationsduetoitslowmemoryfootprint,faststartuptimes,andcompile-timedependencyinjection,makingitsuperiortotraditionalframeworkslikeSpringBootformicroservices,containers,andserverlessenvironments.1.Microna

See all articles