Code & computing / QUICK REFERENCE
TypeScript types, narrowing and generics
Copy practical type declarations, discriminated unions, utility types and generic function patterns.
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();}- Numeric narrowing
if(typeof value==='number'){value.toFixed(2);}- 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);}- Truthy check
if(text){console.log(text.length);}- Discriminated union
type Result = {ok:true;data:string}|{ok:false;error:string};- 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]
Mapped and utility types
- Extract union member
type TextId = Extract<string|number,string>;- Exclude union member
type NumericId = Exclude<string|number,string>;- Non-nullable
type Present = NonNullable<string|null>;- Function return type
type Out = ReturnType<typeof makeItem>;- Function parameter types
type Args = Parameters<typeof makeItem>;
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;}- Generic key accessor
function get<T,K extends keyof T>(o:T,k:K):T[K]{return o[k];}- 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;}- 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;- Union intersection
type Tagged = Item & {tag:string};- Optional generic default
type Response<T=string> = {data:T};
Reserved placement, separate from reference controls. No ad network is active.
No matching entry. Try a shorter word or clear the search to see the complete sheet.
Sources
cheatsheetatlas.com/sheets/typescript/ · Updated 2026-10-20 · TypeScript 6.x · strict