let x: string = "hello" | String type |
let x: number = 42 | Number type |
let x: boolean = true | Boolean type |
let x: null = null | Null type |
let x: undefined = undefined | Undefined type |
let x: symbol = Symbol("id") | Symbol type |
let x: bigint = 100n | BigInt type |
let x: any | Any type (opt-out of type checking) |
let x: unknown | Unknown type (type-safe any) |
function f(): void {} | Void (no return value) |
function f(): never { throw new Error() } | Never (never returns) |
let x: object = {} | Object type (non-primitive) |
let arr: number[] = [1, 2, 3] | Array of numbers |
let arr: Array<string> = ["a", "b"] | Generic array syntax |
let tuple: [string, number] = ["a", 1] | Tuple (fixed length) |
let tuple: [string, ...number[]] | Rest element in tuple |
let arr: readonly number[] | Readonly array |
let arr: ReadonlyArray<number> | ReadonlyArray type |
let tuple: readonly [string, number] | Readonly tuple |
let obj: { name: string; age: number } | Object type literal |
let obj: { name: string; age?: number } | Optional property |
let obj: { readonly id: number } | Readonly property |
let obj: { [key: string]: number } | Index signature |
let obj: { [K in keyof T]: T[K] } | Mapped type |
interface User { name: string; age: number } | Interface declaration |
interface User { age?: number } | Optional property |
interface User { readonly id: number } | Readonly property |
interface Child extends Parent {} | Interface extension |
interface A extends B, C {} | Multiple inheritance |
interface User { [key: string]: any } | Index signature |
interface Fn { (x: number): string } | Function interface |
type ID = string | number | Type alias |
type Point = { x: number; y: number } | Object type alias |
type Callback = (data: string) => void | Function type alias |
type Tree<T> = { value: T; children?: Tree<T>[] } | Recursive type |
type ID = string | number | Union type |
type Status = "pending" | "done" | Literal union |
type Result = Success | Error | Discriminated union |
type A & B | Intersection type |
if (typeof x === "string") {} | typeof guard |
if (x instanceof Date) {} | instanceof guard |
if ("prop" in obj) {} | in operator guard |
if (x === null) {} | Equality narrowing |
if (Array.isArray(x)) {} | Array check |
function isString(x: unknown): x is string | Type predicate |
x as string | Type assertion |
<string>x | Angle-bracket assertion |
x! | Non-null assertion |
let x: "hello" = "hello" | String literal type |
let x: 42 = 42 | Numeric literal type |
let x: true = true | Boolean literal type |
const x = "hello" | const infers literal |
let x = "hello" as const | as const assertion |
const arr = [1, 2] as const | Readonly tuple via as const |
function f(x: string): number {} | Function declaration |
const f = (x: string): number => {} | Arrow function |
const f: (x: string) => number = ... | Function type annotation |
function f(x?: string) {} | Optional parameter |
function f(x: string = "default") {} | Default parameter |
function f(...args: number[]) {} | Rest parameters |
function f(this: User, x: string) {} | this parameter |
function f(x: string): string; | Overload signature 1 |
function f(x: number): number; | Overload signature 2 |
function f(x: string | number) { ... } | Implementation signature |
function f<T>(x: T): T {} | Generic function |
function f<T, U>(x: T, y: U): [T, U] {} | Multiple type params |
function f<T extends object>(x: T) {} | Constrained generic |
function f<T extends { id: number }>(x: T) {} | Interface constraint |
function f<T = string>(x: T) {} | Default type parameter |
const f = <T,>(x: T) => x | Generic arrow function |
interface Box<T> { value: T } | Generic interface |
type Box<T> = { value: T } | Generic type alias |
class Box<T> { value: T } | Generic class |
type Result<T, E = Error> = Success<T> | Failure<E> | Default type param |
T extends string | Extends constraint |
T extends { length: number } | Shape constraint |
T extends U ? X : Y | Conditional type |
K extends keyof T | Keyof constraint |
T extends (...args: any) => infer R | Infer in conditional |
Array<T> | Array of T |
Promise<T> | Promise resolving to T |
Map<K, V> | Map with key K, value V |
Set<T> | Set of T |
Record<K, V> | Object with keys K, values V |
WeakMap<K, V> / WeakSet<T> | Weak references |
Partial<T> | All properties optional |
Required<T> | All properties required |
Readonly<T> | All properties readonly |
Pick<T, K> | Pick specific properties |
Omit<T, K> | Omit specific properties |
Record<K, V> | Object with key type K |
Exclude<T, U> | Remove U from T |
Extract<T, U> | Extract U from T |
NonNullable<T> | Remove null and undefined |
ReturnType<T> | Function return type |
Parameters<T> | Function parameter types |
ConstructorParameters<T> | Constructor param types |
InstanceType<T> | Instance type of class |
ThisParameterType<T> | Type of this param |
OmitThisParameter<T> | Remove this param |
Uppercase<T> | Uppercase string literal |
Lowercase<T> | Lowercase string literal |
Capitalize<T> | Capitalize first letter |
Uncapitalize<T> | Lowercase first letter |
class User { name: string } | Class with property |
class User { private name: string } | Private property |
class User { protected name: string } | Protected property |
class User { readonly id: number } | Readonly property |
class User { #name: string } | ES private field |
class User { static count: number } | Static property |
class User { constructor(public name: string) {} } | Parameter property |
class Child extends Parent {} | Class inheritance |
class User implements IUser {} | Implement interface |
abstract class Base {} | Abstract class |
abstract method(): void | Abstract method |
get name(): string {} | Getter |
set name(value: string) {} | Setter |
override method() {} | Override (explicit) |
class Box<T> { value: T } | Generic class |
class Container<T extends object> {} | Constrained generic |
class Map<K, V> {} | Multiple type params |
class Wrapper<T = string> {} | Default type param |
type Readonly<T> = { readonly [K in keyof T]: T[K] } | Mapped readonly |
{ [K in keyof T]?: T[K] } | Optional mapping |
{ [K in keyof T]-?: T[K] } | Remove optional |
{ -readonly [K in keyof T]: T[K] } | Remove readonly |
{ [K in keyof T as NewKey]: T[K] } | Key remapping |
T extends U ? X : Y | Conditional type |
T extends (...args: any) => infer R ? R : never | Infer return type |
T extends Array<infer U> ? U : never | Infer array element |
T extends Promise<infer U> ? U : T | Unwrap promise |
T extends [infer First, ...infer Rest] ? First : never | Infer tuple parts |
type Greeting = `Hello ${string}` | String pattern type |
type Color = `${R}-${G}-${B}` | Combination type |
type PropEvent<T> = `${T}Changed` | String manipulation |
`on${Capitalize<K>}` | Capitalize in template |
keyof T | Union of keys |
typeof obj | Type of value |
T[K] | Indexed access type |
T[keyof T] | All property types |
typeof arr[number] | Array element type |
const obj = {...} as const; type T = typeof obj | Type from const |
export const x = 1 | Named export |
export default function() {} | Default export |
export { x, y } | Export list |
export { x as y } | Export with rename |
export type { User } | Type-only export |
import { x } from './mod' | Named import |
import x from './mod' | Default import |
import * as mod from './mod' | Namespace import |
import type { User } from './mod' | Type-only import |
export * from './mod' | Re-export all |
declare module "name" {} | Ambient module |
declare global {} | Global augmentation |
declare namespace NS {} | Namespace declaration |
declare function fn(): void | Ambient function |
declare const x: string | Ambient variable |
declare class MyClass {} | Ambient class |
/// <reference types="node" /> | Triple-slash directive |
"strict": true | Enable all strict checks |
"target": "ES2022" | JS output version |
"module": "ESNext" | Module system |
"moduleResolution": "bundler" | Module resolution |
"esModuleInterop": true | CommonJS/ESM interop |
"skipLibCheck": true | Skip .d.ts checking |
"noEmit": true | No JS output |
"declaration": true | Generate .d.ts files |
"sourceMap": true | Generate source maps |
"paths": {"@/*": ["./src/*"]} | Path aliases |
"strictNullChecks": true | Null/undefined checking |
"noImplicitAny": true | Error on implicit any |
"strictFunctionTypes": true | Strict function types |
"strictPropertyInitialization": true | Check class properties |
"noImplicitThis": true | Error on implicit this |
"noUnusedLocals": true | Error on unused locals |
"noUnusedParameters": true | Error on unused params |
"exactOptionalPropertyTypes": true | Exact optional types |
// Type from object keys
const obj = { a: 1, b: 2 } as const;
type Keys = keyof typeof obj; // "a" | "b"
// Discriminated union
type Result =
| { success: true; data: T }
| { success: false; error: Error };
// Type guard function
function isUser(x: unknown): x is User {
return typeof x === "object" && x !== null && "name" in x;
}
// Readonly deep type
type DeepReadonly = {
readonly [K in keyof T]: T[K] extends object
? DeepReadonly
: T[K];
};
// Extract function return type
type AsyncReturn Promise> =
Awaited>; unknown instead of any for type-safe unknown valuesinterface for object types that may be extendedtype for unions, intersections, and mapped typesstrict mode in tsconfig for best type safetyas const for readonly literal types