microsoft / TypeScript-Website

The Website and web infrastructure for learning TypeScript
https://www.typescriptlang.org
Creative Commons Attribution 4.0 International
2.23k stars 1.37k forks source link

Union and UnionType #3227

Closed stanislav-zavistnov closed 1 month ago

stanislav-zavistnov commented 1 month ago

Is there a difference between Union and UnionType in typescript documentation? For example: https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union I'm new to Typescript and in the context of these examples I didn't see any difference, but I might have missed something.

lucaimbalzano commented 1 month ago

I'll provide a detailed explanation highlighting the key differences between Union and UnionType in TypeScript.

Union

A Union in TypeScript refers to the practical use of combining multiple types into one. When you define a union type (like string | number), you're creating a type that can hold values from either of those types. This is a feature that's commonly used in day-to-day TypeScript coding.

type MyUnion = string | number;

UnionType

UnionType refers to an internal concept in TypeScript's type system. It is not something you directly interact with when writing normal TypeScript code. Instead, UnionType comes into play when TypeScript handles union types behind the scenes, especially in more advanced or internal utilities like Exclude or Extract.

For example, let’s look at the source code for Exclude and Extract:

/**
 * Exclude from T those types that are assignable to U
 */
type Exclude<T, U> = T extends U ? never : T;

/**
 * Extract from T those types that are assignable to U
 */
type Extract<T, U> = T extends U ? T : never;

In both Exclude and Extract, the generic types T and U can be union types. The TypeScript compiler uses UnionType internally to evaluate how to exclude or extract specific types within those unions.

In Few Words

Example

type MyUnion = string | number;
type ExcludeNumber = Exclude<MyUnion, number>; // Result: string
type ExtractString = Extract<MyUnion, string>; // Result: string

Let me know if is more clear now 👋

jakebailey commented 1 month ago

To be clear, the names given on the linked doc pages are just the names of type variables. They don't have anything to do with the internal concepts of the compiler itself, they're just there to tell you what the type variables of the helper type mean.