Skip to content

Typescript All Operators

  • A complete Typescript language reference
OperatorSymbolNamePurposeExample
??Optional Property/ParameterMarks properties or parameters as optionalinterface User { name?: string }
function greet(name?: string) {}
!!Non-null AssertionAsserts that a value is not null/undefinedconst element = document.getElementById('myEl')!;
element.focus(); // No null check needed
?.?.Optional ChainingSafely access nested propertiesconst city = user?.address?.city;
// undefined if user or address is null
????Nullish CoalescingProvides default for null/undefinedconst name = inputName ?? 'Anonymous';
// Uses 'Anonymous' only if inputName is null/undefined
&&Intersection TypeCombines multiple typestype Admin = User & { permissions: string[] };
// Has both User properties and permissions
||Union TypeRepresents one of several typestype ID = string | number;
let id: ID = 123; id = 'abc';
asasType AssertionExplicit type conversionconst length = (someValue as string).length;
const element = el as HTMLInputElement;
keyofkeyofKeyof OperatorGets keys of a typetype UserKeys = keyof User; // 'name' | 'age' | 'email'
function getProp<T>(obj: T, key: keyof T) {}
typeoftypeofTypeof OperatorGets type of a valueconst user = { name: 'John', age: 30 };
type UserType = typeof user; // { name: string; age: number }
ininIn OperatorChecks property existenceif ('name' in user) { console.log(user.name); }
// Type-safe property check
extendsextendsConstraint OperatorConstrains generic typesfunction logLength<T extends { length: number }>(obj: T) {}
// T must have length property
inferinferInfer KeywordInfers types in conditionalstype ArrayType<T> = T extends (infer U)[] ? U : never;
type Num = ArrayType<number[]>; // number
readonlyreadonlyReadonly ModifierMakes properties read-onlyinterface Point { readonly x: number; readonly y: number; }
point.x = 5; // Error!
-?-?Required ModifierRemoves optionalitytype Required<T> = { [P in keyof T]-?: T[P] };
// Makes all properties required
-readonly-readonlyMutable ModifierRemoves readonlytype Mutable<T> = { -readonly [P in keyof T]: T[P] };
// Makes all properties mutable
satisfiessatisfiesSatisfies OperatorValidates without wideningconst colors = ['red', 'green'] satisfies string[];
// Type is string[], not (string | number)[]
SymbolNamePurposeExample
*Import/Export WildcardImport/export all from moduleimport * as React from 'react';
export * from './utils';
...Rest/SpreadRest parameters or spread elementsfunction sum(...numbers: number[]) {}
const newArr = [...oldArr, newItem];
[]Index SignatureDynamic object propertiesinterface Dictionary { [key: string]: string; }
const dict: Dictionary = { hello: 'world' };
<>Type ParametersGeneric type parametersfunction identity<T>(value: T): T {}
type Response<T> = { data: T };
@DecoratorMetadata/annotation@Component({ selector: 'app-root' })
class AppComponent {}
#Private FieldClass private fieldsclass User { #password: string; }
// Truly private, not just TypeScript-private
_Numeric SeparatorReadable numbersconst million = 1_000_000;
const hex = 0xFF_FF_FF;
//Single-line CommentComments// This is a comment
const x = 5; // inline comment
/* */Multi-line CommentBlock comments/* This is a
multi-line comment */
OperatorPurposeExampleResult
`...`Template Literal`Hello ${name}!`String interpolation with variables
Capitalize<T>Capitalizetype Cap = Capitalize<'hello'>;'Hello'
Uncapitalize<T>Uncapitalizetype Uncap = Uncapitalize<'Hello'>;'hello'
Uppercase<T>Uppercasetype Upper = Uppercase<'hello'>;'HELLO'
Lowercase<T>Lowercasetype Lower = Lowercase<'HELLO'>;'hello'
OperatorPurposeExample
inIterate over keystype Optional<T> = { [K in keyof T]?: T[K] };
// Makes all properties optional
asKey remappingtype Getters<T> = { [K in keyof T as get${K}]: T[K] };
// Creates getter methods
?Add optionalitytype Partial<T> = { [K in keyof T]?: T[K] };
// All properties optional
-?Remove optionalitytype Required<T> = { [K in keyof T]-?: T[K] };
// All properties required
readonlyAdd readonlytype Readonly<T> = { readonly [K in keyof T]: T[K] };
// All properties readonly
-readonlyRemove readonlytype Mutable<T> = { -readonly [K in keyof T]: T[K] };
// All properties mutable
OperatorPurposeExample
importImport moduleimport { Component } from 'react';
import React from 'react';
exportExport memberexport function util() {}
export const PI = 3.14;
export defaultDefault exportexport default class MyClass {}
export default function() {}
export *Re-export allexport * from './math-utils';
// Re-exports all named exports
export * asRe-export as namespaceexport * as Utils from './utils';
// Creates Utils namespace
import typeType-only importimport type { User } from './types';
// Only imports type, no runtime code
import()Dynamic importconst module = await import('./my-module');
// Code splitting
OperatorPurposeExample
extends ? :Conditional typetype IsString<T> = T extends string ? true : false;
type Test = IsString<'hello'>; // true
inferType inferencetype First<T> = T extends [infer U, ...unknown[]] ? U : never;
type F = First<[1, 2, 3]>; // 1
neverBottom typetype Exclude<T, U> = T extends U ? never : T;
// Excludes types from union
anyTop typelet anything: any = 'could be anything';
anything = 42; // No type checking
unknownSafe top typelet unsure: unknown = 'hello';
// Needs type checking before use
OperatorPurposeExample
Partial<T>Make all optionaltype PartialUser = Partial<User>;
// All User properties become optional
Required<T>Make all requiredtype RequiredUser = Required<PartialUser>;
// All properties become required
Readonly<T>Make all readonlytype ReadonlyUser = Readonly<User>;
// All properties become readonly
Pick<T, K>Pick propertiestype NameOnly = Pick<User, 'name'>;
// { name: string }
Omit<T, K>Omit propertiestype WithoutId = Omit<User, 'id'>;
// All properties except id
Record<K, T>Object with key typetype UserMap = Record<string, User>;
// { [key: string]: User }
Exclude<T, U>Exclude from uniontype Numbers = Exclude<string | number, string>;
// number
Extract<T, U>Extract from uniontype Strings = Extract<string | number, string>;
// string
NonNullable<T>Remove null/undefinedtype Clean = NonNullable<string | null>;
// string
Parameters<T>Function parameterstype Params = Parameters<(a: number, b: string) => void>;
// [number, string]
ReturnType<T>Function return typetype Return = ReturnType<() => string>;
// string
InstanceType<T>Constructor instanceclass User {}
type UserInstance = InstanceType<typeof User>;
Awaited<T>Unwrap Promisetype Result = Awaited<Promise<string>>;
// string
OperatorPurposeExample
as constConst assertionconst colors = ['red', 'green'] as const;
// Type: readonly ['red', 'green']
literalLiteral typetype Status = 'active' | 'inactive';
let status: Status = 'active';
template literalTemplate typetype Email = `${string}@${string}.${string}`;
let email: Email = 'user@example.com';