Code & computing / QUICK REFERENCE

TypeScript types, narrowing and generics

Copy practical type declarations, discriminated unions, utility types and generic function patterns.

54 entries

Common types and objects

String variable
const name: string = 'Ada';

Constrains a binding to string values. [1]

Number variable
const age: number = 36;

Number includes integer and floating-point values. [1]

Boolean variable
const enabled: boolean = true;

Restricts value to true or false. [1]

Number array
const ids: number[] = [1,2];

Array elements must be compatible with number. [1]

Alternative array syntax
const ids: Array<number> = [1,2];

Generic Array notation means the same element type. [1]

Readonly array
const ids: readonly number[] = [1,2];

Prevents array mutation through that typed reference. [1]

Fixed tuple
const point: [number,number] = [2,3];

Tuple fixes the positional element types. [1]

Optional field
type User = {id:number; email?:string};

Property email can be absent or undefined. [1]

Readonly field
type User = {readonly id:number};

Blocks assignment to id through that type. [1]

Union
type Id = string | number;

Accepts one of the listed possible types. [1]

Literal union
type State = 'open'|'closed';

Limits values to two literal strings. [1]

Function signature
type Handler = (value:string)=>void;

Describes an argument and no useful return value. [1]

Named interface
interface Item {id:number; name:string}

Describes properties required by matching objects. [1]

Extending interface
interface Admin extends Item {role:string}

Adds properties to an existing interface. [1]

Narrow unknown values safely

String narrowing
if(typeof value==='string'){value.toUpperCase();}

TypeScript narrows a union within the true branch. [2][1]

Numeric narrowing
if(typeof value==='number'){value.toFixed(2);}

Number-only methods become available after check. [2][1]

Array narrowing
if(Array.isArray(value)){value.length;}

Runtime Array check narrows unknown to an array type. [2][1]

Non-null guard
if(value != null){console.log(value);}

Loose inequality excludes both null and undefined. [2][1]

Truthy check
if(text){console.log(text.length);}

Be careful: empty strings also count as falsy. [2][1]

Discriminated union
type Result = {ok:true;data:string}|{ok:false;error:string};

Literal discriminant helps control-flow narrowing. [2][1]

Check discriminant
if(result.ok){console.log(result.data);}

Inside this branch only the successful union member remains. [2][1]

In operator guard
if('name' in value){console.log(value.name);}

Property existence can narrow suitable object union types. [2][1]

Use unknown
const payload: unknown = JSON.parse(raw);

Unknown forces runtime checks before property access. [2][1]

Avoid blind any
const payload: any = JSON.parse(raw);

Any bypasses type checking and should be narrowly limited. [2][1]

Safe assertion
const element = document.getElementById('x') as HTMLInputElement;

Asserting is compile-time only and cannot validate runtime structure. [2][1]

Non-null assertion
element!.focus();

Exclamation removes nullish type warnings without runtime protection. [2][1]

Exhaustive never
const unreachable: never = state;

Used after complete union branching to catch unhandled variants. [2][1]

Optional chain
const zip = user.address?.zip;

Access may yield undefined when address is absent. [2][1]

Mapped and utility types

Make optional
type Draft = Partial<Item>;

All Item properties become optional. [3][1]

Make required
type Complete = Required<User>;

All optional properties become required. [3][1]

Make readonly
type Frozen = Readonly<Item>;

Prevents assignments through that typed view. [3][1]

Pick fields
type Brief = Pick<Item,'id'|'name'>;

Keeps only named keys from Item. [3][1]

Omit field
type PublicUser = Omit<User,'secret'>;

Removes a named property from User type. [3][1]

Keyed dictionary
type Scores = Record<string,number>;

Maps string keys to numeric values. [3][1]

Extract union member
type TextId = Extract<string|number,string>;

Keeps members assignable to string. [3][1]

Exclude union member
type NumericId = Exclude<string|number,string>;

Removes members assignable to string. [3][1]

Non-nullable
type Present = NonNullable<string|null>;

Removes null and undefined union members. [3][1]

Function return type
type Out = ReturnType<typeof makeItem>;

Infers return from function makeItem. [3][1]

Function parameter types
type Args = Parameters<typeof makeItem>;

Produces a tuple of function parameter types. [3][1]

Awaited type
type ResultValue = Awaited<Promise<string>>;

Unwraps the promised value type. [3][1]

Type key union
type ItemKey = keyof Item;

Produces union of property names on Item. [3][1]

Indexed property type
type ItemName = Item['name'];

Retrieves the type of a particular property. [3][1]

Generics and expressive patterns

Generic identity
function identity<T>(x:T):T{return x;}

Inferred type parameter relates argument to return type. [4][1]

Generic array head
function first<T>(xs:T[]):T|undefined{return xs[0];}

Handles empty arrays without making a false guarantee. [4][1]

Constrain generic
function len<T extends {length:number}>(x:T){return x.length;}

Accepts values with numeric length property. [4][1]

Generic container
type Box<T> = {value:T};

Caller chooses contained value type. [4][1]

Generic key accessor
function get<T,K extends keyof T>(o:T,k:K):T[K]{return o[k];}

Guarantees the selected key exists on T. [4][1]

Async return type
async function load():Promise<string>{return 'ok';}

Async functions return Promise of the declared value. [4][1]

Function overload
function parse(x:string):string; function parse(x:number):number; function parse(x:string|number){return x;}

Overload signatures constrain caller-visible inputs. [4][1]

Satisfies operator
const config = {mode:'dark'} satisfies {mode:string};

Checks compatibility while keeping inferred expression type. [4][1]

Const assertion
const directions = ['up','down'] as const;

Infers readonly tuple with literal values. [4][1]

Union intersection
type Tagged = Item & {tag:string};

Intersection must satisfy both structural types. [4][1]

Optional generic default
type Response<T=string> = {data:T};

Uses default type argument when omitted. [4][1]

Type predicate
function isString(x:unknown):x is string{return typeof x==='string';}

Type guard aids narrowing after runtime check. [4][1]

Reserved placement, separate from reference controls. No ad network is active.

Updated TypeScript 6.x · strict

Sources

  1. Everyday types ↗
  2. Narrowing ↗
  3. Utility types ↗
  4. Generics ↗