亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Union Types: Handling Multiple Possibilities
Practical Example: Status Handling
Intersection Types: Combining Types
Real-World Use Case: Mixins or Configuration Objects
The never Type: Representing Unreachable States
1. Functions That Never Return
2. Exhaustiveness Checking in Unions
How never Works in Type Systems
Putting It All Together
Summary
Home Backend Development PHP Tutorial Advanced Type Hinting: Union Types, Intersection Types, and `never`

Advanced Type Hinting: Union Types, Intersection Types, and `never`

Jul 29, 2025 am 12:48 AM
PHP Syntax

Union types (A | B) allow a value to be one of several types, enabling flexible handling of multiple input possibilities. 2. Intersection types (A & B) combine multiple types into one that must satisfy all members, useful for creating complex object shapes. 3. The never type represents unreachable or impossible states, commonly used in exhaustiveness checks and functions that never return. Together, these advanced TypeScript features enable more robust, self-documenting, and type-safe code by making invalid states unrepresentable.

Advanced Type Hinting: Union Types, Intersection Types, and `never`

When working with TypeScript, basic type annotations are just the beginning. To write more robust, expressive, and maintainable code, you need to go beyond string, number, or boolean and leverage advanced type hints like union types, intersection types, and the special never type. These tools give you fine-grained control over how values and functions behave in complex scenarios.

Let’s break down each of these concepts with practical examples and use cases.


Union Types: Handling Multiple Possibilities

A union type allows a value to be one of several types. You define it using the vertical bar (|).

let userId: string | number;
userId = "abc123"; // ?
userId = 123;       // ?

This is especially useful when dealing with APIs, user input, or legacy data where the type isn’t guaranteed.

Practical Example: Status Handling

function getStatus(status: "loading" | "success" | "error") {
  // ...
}
getStatus("loading"); // ?
getStatus("pending"); // ? Argument not assignable

You can also use unions with complex types:

type User = { name: string; age: number };
type Admin = { name: string; permissions: string[] };

function printInfo(entity: User | Admin) {
  console.log(entity.name); // ? 'name' exists on both
  // console.log(entity.age); // ? Error: 'age' not on Admin
}

? Tip: Use a type guard to narrow down union types at runtime.

if ("age" in entity) {
  console.log(entity.age); // Now safe
}

Intersection Types: Combining Types

An intersection type combines multiple types into one. It uses the & operator and means “this value must satisfy all types.”

type User = { name: string; email: string };
type Timestamp = { createdAt: Date; updatedAt: Date };

type UserWithTimestamp = User & Timestamp;

const user: UserWithTimestamp = {
  name: "Alice",
  email: "alice@example.com",
  createdAt: new Date(),
  updatedAt: new Date(),
};

Real-World Use Case: Mixins or Configuration Objects

type WithId = { id: number };
type WithName = { name: string };
type Active = { isActive: boolean };

type Account = WithId & WithName & Active;

const account: Account = {
  id: 1,
  name: "Pro User",
  isActive: true,
};

?? Be careful with object intersections that have conflicting fields:

type A = { data: string };
type B = { data: number };
type C = A & B;

const example: C = {
  data: ??? // What could this be? Must be string & number → impossible → `never`
};

Which leads us to…


The never Type: Representing Unreachable States

The never type represents values that should never occur. It’s used in two main scenarios:

  1. Functions that never return
  2. Values that can’t exist due to type narrowing

1. Functions That Never Return

function throwError(message: string): never {
  throw new Error(message);
}

This function doesn’t just return void — it never returns. TypeScript uses never to model that.

2. Exhaustiveness Checking in Unions

A classic use of never is ensuring all cases are handled in a union:

type Mode = "dark" | "light" | "auto";

function getTheme(mode: Mode) {
  switch (mode) {
    case "dark":
      return "Black";
    case "light":
      return "White";
    case "auto":
      return window.prefersDark ? "Black" : "White";
    default:
      // If all cases are covered, `mode` becomes `never` here
      const _exhaustiveCheck: never = mode;
      return _exhaustiveCheck;
  }
}

If you later add a new value to Mode but forget to handle it, this line will throw a type error, helping you catch incomplete logic.

How never Works in Type Systems

  • never is the bottom type — it can be assigned to any type.
  • But no type can be assigned to never (except never itself).
  • It appears during type narrowing when possibilities are exhausted.
function handleValue(x: string | number) {
  if (typeof x === "string") {
    // x is string
  } else if (typeof x === "number") {
    // x is number
  } else {
    // x is `never` — no other possibility
    const unexpected: never = x;
    throw new Error(`Unexpected value: ${unexpected}`);
  }
}

Putting It All Together

Imagine building a form validation system:

type Success = { success: true; data: string };
type Failure = { success: false; error: string };
type Result = Success & Failure; // Wait — what?

// That doesn’t make sense. Instead:
type ValidationResult = Success | Failure;

function isValid(input: string): ValidationResult {
  if (input.length > 0) {
    return { success: true, data: input };
  } else {
    return { success: false, error: "Empty input" };
  }
}

// Then, handle the result safely:
function processResult(res: ValidationResult) {
  if (res.success) {
    console.log("Data:", res.data); // ? Type is Success
  } else {
    console.log("Error:", res.error); // ? Type is Failure
  }
}

Here, union types enable conditional typing, and TypeScript narrows the type based on the success field.


Summary

  • Union types (A | B): Value is either A or B — great for flexible inputs.
  • Intersection types (A & B): Value must be both A and B — useful for combining features.
  • never: Represents impossible or unreachable states — essential for exhaustiveness checks and error functions.

These advanced type features help you write safer code by making invalid states unrepresentable. Once you get comfortable with them, your TypeScript becomes not just typed — it becomes self-documenting and self-enforcing.

Basically, that’s how you level up from basic annotations to truly powerful type modeling.

The above is the detailed content of Advanced Type Hinting: Union Types, Intersection Types, and `never`. 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
1488
72
An Introduction to PHP 8 Attributes: Replacing DocBlocks with Structured Metadata An Introduction to PHP 8 Attributes: Replacing DocBlocks with Structured Metadata Jul 25, 2025 pm 12:27 PM

PHP8attributesreplaceDocBlocksformetadatabyprovidingtype-safe,nativelysupportedannotations.1.Attributesaredefinedusing#[Attribute]andcantargetclasses,methods,properties,etc.2.Theyenablecompile-timevalidation,IDEsupport,andbetterperformancebyeliminati

Is PHP syntax easy? Is PHP syntax easy? Jul 17, 2025 am 04:12 AM

Yes,PHPsyntaxiseasy,especiallyforbeginners,becauseitisapproachable,integrateswellwithHTML,andrequiresminimalsetup.Itssyntaxisstraightforward,allowingdirectembeddingintoHTMLwithtags,using$forvariables,semicolonsforstatements,andfamiliarC-stylestructur

Mastering PHP Array Destructuring and the Spread Operator Mastering PHP Array Destructuring and the Spread Operator Jul 25, 2025 am 04:44 AM

PHP's array deconstruction and expansion operators can improve code readability and flexibility through concise syntax. 1. Array deconstruction supports extracting values from indexes and associative arrays, such as [$first,$second]=$colors, which can be assigned separately; elements can be skipped through empty placeholders, such as [,,$third]=$colors; associative array deconstruction requires the => matching key, such as ['name'=>$name]=$user, which supports renaming variables and setting default values to deal with missing keys. 2. Expand operator (...) can expand and merge arrays, such as [...$colors,'blue'], which supports majority combination and associative array overwrite, but subsequent keys will overwrite the former and do not replenish.

Leveraging Named Arguments and Constructor Property Promotion in Modern PHP Leveraging Named Arguments and Constructor Property Promotion in Modern PHP Jul 24, 2025 pm 10:28 PM

PHP8.0'snamedargumentsandconstructorpropertypromotionimprovecodeclarityandreduceboilerplate:1.Namedargumentsletyoupassparametersbyname,enhancingreadabilityandallowingflexibleorder;2.Constructorpropertypromotionautomaticallycreatesandassignsproperties

Static vs. Self: Unraveling Late Static Bindings in PHP Static vs. Self: Unraveling Late Static Bindings in PHP Jul 26, 2025 am 09:50 AM

When a static method is called using self in inheritance, it always points to the class that defines the method, rather than the actually called class, resulting in the inability to call the subclass overridden method as expected; while static uses late static binding, which can correctly parse to the actually called class at runtime. 1. Self is an early binding, pointing to the class where the code is located; 2. static is a late binding, pointing to the runtime calling class; 3. Use static to implement static factory methods and automatically return subclass instances; 4. static supports correct resolution of inherited attributes in the method chain; 5. LSB is only suitable for static methods and attributes, not for constants; 6. Static should be used first in inheritable classes to improve flexibility and scalability, which is in modern PH

Understanding Variadic Functions and Argument Unpacking in PHP Understanding Variadic Functions and Argument Unpacking in PHP Jul 25, 2025 am 04:50 AM

PHP's variable functions and parameter unpacking is implemented through the splat operator (...). 1. Variable functions use...$params to collect multiple parameters as arrays, which must be at the end of the parameter list and can coexist with the required parameters; 2. Parameter unpacking uses...$array to expand the array into independent parameters and pass it into the function, suitable for numerical index arrays; 3. The two can be used in combination, such as passing parameters in the wrapper function; 4. PHP8 supports matching named parameters when unpacking associative arrays, and it is necessary to ensure that the key name is consistent with the parameter name; 5. Pay attention to avoid using unpacking for non-traversable data, prevent fatal errors, and pay attention to the limit of parameter quantity. These features improve code flexibility and readability, reducing func_get_args() and so on

Demystifying PHP's Ternary, Null Coalescing, and Nullsafe Operators Demystifying PHP's Ternary, Null Coalescing, and Nullsafe Operators Jul 25, 2025 pm 04:48 PM

Theternaryoperator(?:)isusedforsimpleif-elselogic,returningoneoftwovaluesbasedonacondition;2.Thenullcoalescingoperator(??)returnstheleftoperandifitisnotnullorundefined,otherwisetherightoperand,makingitidealforsettingdefaultswithoutbeingaffectedbyfals

PHP Anonymous Functions vs. Arrow Functions: A Syntax Deep Dive PHP Anonymous Functions vs. Arrow Functions: A Syntax Deep Dive Jul 25, 2025 pm 04:55 PM

Arrow functions are suitable for scenarios with single expressions, simple callbacks and improved readability; 2. Anonymous functions are suitable for scenarios with multi-line logic, complex control flow, referencing external variables and using yield generators; therefore, you should choose according to specific needs: simple scenarios prioritize arrow functions to improve code simplicity, while complex scenarios use anonymous functions to obtain complete functional support.

See all articles