liveBook · Manning

User-defined type

As explained in React in Depth

A custom type is a programmer-defined type specification that restricts or describes the values permitted in a program.

A user-defined type is a programmer-named specification of permitted values. In TypeScript, it makes variables, function results, and component inputs explicit while allowing the compiler to reject invalid assignments before runtime. section 5.2.2

Use the narrowest useful definition for the value being modeled:

  • Combine alternatives when a value may have different forms, such as null or a string: type Name = null | string. section 5.2.2
  • Restrict a value to specific literals, such as LOADING, SUCCESS, or ERROR, so unsupported states become type errors. section 5.2.2
  • Describe structured React component inputs with a type alias or interface, marking optional properties with ?. section 5.2.2
  • Prefer unknown when an external value has an unverified type; avoid any when its unrestricted behavior would remove useful checking. section 5.2.2

Constrain a status and component props

type Status = "LOADING" | "SUCCESS" | "ERROR"; let status: Status = "LOADING"; interface PersonProps { name?: string; age?: number; } function Person({ name = "Anonymous", age }: PersonProps) { // ... } status = "COMPLETE"; // TypeScript error The literal union rejects values outside the declared state set, while the interface documents optional component inputs and supports a default name. section 5.2.2

type Status = "LOADING" | "SUCCESS" | "ERROR";
let status: Status = "LOADING";

Inspect the compact literal-union definition used to constrain status values. section 5.2.2

type PersonProps = {
  name: string;
  age: number;
};
function Person({ name, age }: PersonProps) {
  ...
}

Inspect the typed React component props pattern. section 5.2.2

How React in Depth covers it

How deep it goes
Explains unions, literal values, interfaces, optional properties, and unknown, but defers technical differences between interfaces and type aliases.
Examples
Uses nullable names, status literals, invalid assignments, and typed React component props with optional fields.
What it assumes
Assumes basic TypeScript and React functions while teaching custom type syntax from the examples.
What you can do after
Apply it via TypeScript to reject invalid values and document React component interfaces.
How it connects
Connects user-defined types to TypeScript, type inference, union types, interfaces, and React components.

Also explained in

Compare how 5 books explain user-defined type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.