AI Briefing
KO

TypeScript Type System Explained: Structural Typing, Union/Intersection Types, and Object Literal Checks

·2022.11.24 09:00

Key point

This article explains structural typing, union/intersection types, template literal types, and strict object literal checking rules with examples.

1 / 2

Details

TypeScript adopts a Structural Type System, determining assignability based on structure rather than name during type comparison. For example, if the User and Admin classes have the same method structure, they can be assigned to each other; an error occurs only when the structures are incompatible, such as when a return type changes from number to boolean.

Type Constraints and Unit Types

Types are defined as sets of assignable values. You can specify a broad range like type Role = string, while a type holding a single primitive value, such as type AdminRole = "manager", is called a Unit type. Variables declared with let are inferred as broad types (string), which may cause errors when assigned to unit type parameters, but declaring them with const narrows the type (narrowing), allowing the assignment.

Union and Intersection Types

A union type (|) is a set union, allowing a value to be one of several types. An intersection type (&) is a set intersection, retaining only values assignable to both types. The intersection of a supertype and a subtype results in the subtype, while the union results in the supertype. The intersection of the any type with other types results in any, except when intersected with never.

Template Literal Types

In TypeScript 4.5 and later, template literal types allow dynamic generation of string combinations. Combined with the Capitalize utility type, it is easy to create types in camelCase format.

Strict Checking of Object Literals

Under the principles of structural typing, objects with additional properties can be assigned if they include the target type's properties. However, when assigning an object literal directly to a variable, the 'Excess Property Check' is applied, causing an error if undefined properties are present. This check does not apply when assigning indirectly through a variable.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.