Usage |
Install |
npm install TypeScript
|
Run |
npx tsc
|
Run with a specific config |
npx tsc --project configs/my_tsconfig.json
|
Triple slash directives |
Reference built-in types |
|
Reference other types |
|
AMD |
|
Compiler comments |
Don’t check this file |
|
Check this file (JS) |
|
Ignore the next line |
|
Expect an error on the next line |
|
Operators (TypeScript-specific and draft JavaScript) |
?? (nullish coalescing) |
function getValue(val?: number): number | 'nil' {
return val ?? 'nil';
}
|
?. (optional chaining) |
function countCaps(value?: string) {
return value?.match(/[A-Z]/g)?.length ?? 0;
}
|
! (null assertion) |
let value: string | undefined;
console.log(`value is ${value!.length} characters long`);
|
&&= |
let a;
let b = 1;
a &&= 'default';
b &&= 5;
|
||= |
let a;
let b = 1;
a ||= 'default';
b ||= 5;
|
??= |
let a;
let b = 0;
a ??= 'default';
b ??= 5;
|
Basic types |
Untyped |
any
|
A string |
string
|
Template string |
${string}Suffix
|
A number |
number
|
A true / false value |
boolean
|
A non-primitive value |
object
|
Uninitialized value |
undefined
|
Explicitly empty value |
null
|
Null or undefined (usually only used for function returns) |
void
|
A value that can never occur |
never
|
A value with an unknown type |
unknown
|
Object types |
Object |
{
requiredStringVal: string;
optionalNum?: number;
readonly readOnlyBool: bool;
}
|
Object with arbitrary string properties (like a hashmap or dictionary) |
{ [key: string]: Type; }
{ [key: number]: Type; }
{ [key: symbol]: Type; }
{ [key: `data-${string}`]: Type; }
|
Literal types |
String |
let direction: 'left' | 'right';
|
Numeric |
let roll: 1 | 2 | 3 | 4 | 5 | 6;
|
Arrays and tuples |
Array of strings |
string[]
or
Array<string>
|
Array of functions that return strings |
(() => string)[]
or
{ (): string; }[]
or
Array<() => string>
|
Basic tuples |
let myTuple: [ string, number, boolean? ];
myTuple = [ 'test', 42 ];
|
Variadic tuples |
type Numbers = [number, number];
type Strings = [string, string];
type NumbersAndStrings = [...Numbers, ...Strings];
type NumberAndRest = [number, ...string[]];
type RestAndBoolean = [...any[], boolean];
|
Named tuples |
type Vector2D = [x: number, y: number];
function createVector2d(...args: Vector2D) {}
|
Functions |
Function type |
(arg1: Type, argN: Type) => Type;
or
{ (arg1: Type, argN: Type): Type; }
|
Constructor |
new () => ConstructedType;
or
{ new (): ConstructedType; }
|
Function type with optional param |
(arg1: Type, optional?: Type) => ReturnType
|
Function type with rest param |
(arg1: Type, ...allOtherArgs: Type[]) => ReturnType
|
Function type with static property |
{ (): Type; staticProp: Type; }
|
Default argument |
function fn(arg1 = 'default'): ReturnType {}
|
Arrow function |
(arg1: Type): ReturnType => { ...; return value; }
or
(arg1: Type): ReturnType => value;
|
this typing |
function fn(this: Foo, arg1: string) {}
|
Overloads |
function conv(a: string): number;
function conv(a: number): string;
function conv(a: string | number): string | number {
...
}
|
Union and intersection types |
Union |
let myUnionVariable: number | string;
|
Intersection |
let myIntersectionType: Foo & Bar;
|
Named types |
Interface |
interface Child extends Parent, SomeClass {
property: Type;
optionalProp?: Type;
optionalMethod?(arg1: Type): ReturnType;
}
|
Class |
class Child
extends Parent
implements Child, OtherChild {
property: Type;
defaultProperty = 'default value';
private _privateProperty: Type;
private readonly _privateReadonlyProperty: Type;
static staticProperty: Type;
static {
try {
Child.staticProperty = calcStaticProp();
} catch {
Child.staticProperty = defaultValue;
}
}
constructor(arg1: Type) {
super(arg1);
}
private _privateMethod(): Type {}
methodProperty: (arg1: Type) => ReturnType;
overloadedMethod(arg1: Type): ReturnType;
overloadedMethod(arg1: OtherType): ReturnType;
overloadedMethod(arg1: CommonT): CommonReturnT {}
static staticMethod(): ReturnType {}
subclassedMethod(arg1: Type): ReturnType {
super.subclassedMethod(arg1);
}
}
|
Enum |
enum Options {
FIRST,
EXPLICIT = 1,
BOOLEAN = Options.FIRST | Options.EXPLICIT,
COMPUTED = getValue()
}
enum Colors {
Red = "#FF0000",
Green = "#00FF00",
Blue = "#0000FF"
}
|
Type alias |
type Name = string;
type Direction = 'left' | 'right';
type ElementCreator = (type: string) => Element;
type Point = { x: number, y: number };
type Point3D = Point & { z: number };
type PointProp = keyof Point;
const point: Point = { x: 1, y: 2 };
type PtValProp = keyof typeof point;
|
Generics |
Function using type parameters |
<T>(items: T[], callback: (item: T) => T): T[]
|
Interface with multiple types |
interface Pair<T1, T2> {
first: T1;
second: T2;
}
|
Constrained type parameter |
<T extends ConstrainedType>(): T
|
Default type parameter |
<T = DefaultType>(): T
|
Constrained and default type parameter |
<T extends ConstrainedType = DefaultType>(): T
|
Generic tuples |
type Arr = readonly any[];
function concat<U extends Arr, V extends Arr>(a: U, b: V):
[...U, ...V] { return [...a, ...b] }
const strictResult = concat([1, 2] as const, ['3', '4'] as const);
const relaxedResult = concat([1, 2], ['3', '4']);
|
Index, mapped, and conditional types |
Index type query (keyof ) |
type Point = { x: number, y: number };
let pointProp: keyof Point = 'x';
function getProp<T, K extends keyof T>(
val: T,
propName: K
): T[K] { ... }
|
Mapped types |
type Stringify<T> = { [P in keyof T]: string; }
type Partial<T> = { [P in keyof T]?: T[P]; }
|
Conditional types |
type Swapper = <T extends number | string>
(value: T) => T extends number ? string : number;
is equivalent to
(value: number) => string
if T is number, or
(value: string) => number
if T is string
|
Conditional mapped types |
interface Person {
firstName: string;
lastName: string;
age: number;
}
type StringProps<T> = {
[K in keyof T]: T[K] extends string ? K : never;
};
type PersonStrings = StringProps<Person>;
|
Utility types |
Awaited |
type A = Awaited<Promise<string>>;
type B = Awaited<Promise<Promise<number>>>;
type C = Awaited<boolean | Promise<number>>;
|
Partial |
Partial<{ x: number; y: number; z: number; }>
is equivalent to
{ x?: number; y?: number; z?: number; }
|
Readonly |
Readonly<{ x: number; y: number; z: number; }>
is equivalent to
{
readonly x: number;
readonly y: number;
readonly z: number;
}
|
Pick |
Pick<{ x: number; y: number; z: number; }, 'x' | 'y'>
is equivalent to
{ x: number; y: number; }
|
Record |
Record<'x' | 'y' | 'z', number>
is equivalent to
{ x: number; y: number; z: number; }
|
Exclude |
type Excluded = Exclude<string | number, string>;
is equivalent to
number
|
Extract |
type Extracted = Extract<string | number, string>;
is equivalent to
string
|
NonNullable |
type NonNull = NonNullable<string | number | void>;
is equivalent to
string | number
|
ReturnType |
type ReturnValue = ReturnType<() => string>;
is equivalent to
string
|
InstanceType |
class Renderer() {}
type Instance = InstanceType<typeof Renderer>;
is equivalent to
Renderer
|
Type guards |
Type predicates |
function isThing(val: unknown): val is Thing {
}
if (isThing(value)) {
}
|
typeof |
declare value: string | number | boolean;
const isBoolean = typeof value === “boolean”;
if (typeof value === "number") {
} else if (isBoolean) {
} else {
}
|
instanceof |
declare value: Date | Error | MyClass;
const isMyClass = value instanceof MyClass;
if (value instanceof Date) {
} else if (isMyClass) {
} else {
}
|
in |
interface Dog { woof(): void; }
interface Cat { meow(): void; }
function speak(pet: Dog | Cat) {
if ('woof' in pet) {
pet.woof()
} else {
pet.meow()
}
}
|
Assertions |
Type |
let val = someValue as string;
or
let val = <string>someValue;
|
Const (immutable value) |
let point = { x: 20, y: 30 } as const;
or
let point = <const>{ x: 20, y: 30 };
|
Ambient declarations |
Global |
declare const $: JQueryStatic;
|
Module |
declare module "foo" {
export class Bar { ... }
}
|
Wildcard module |
declare module "text!*" {
const value: string;
export default value;
}
|