TypeScript

Type vs Interface
Type can be a primitive, a union, or a tuple. It cannot be changed after creation
// primitive type Name = string; // union type PartialPoint = PartialPointX | PartialPointY; // tuple type Data = [number, string];
Interface only describes an object, and repeated declarations are merged (declaration merging)
Extension & Intersection
Intersection
type Shape = { color: string }; type Circle = Shape & { role: string };
Extension
Same as intersection, but the syntax is closer to OOP
interface Shape { color: string; } interface Circle extends Shape { radius: number; }
Implements
Both type and interface can be used in implements
interface Point { x: number; y: number; } class SomePoint implements Point { x = 1; y = 2; } // same type Point2 = { x: number; y: number; }; class SomePoint2 implements Point2 { x = 1; y = 2; }
Declaration merging
Repeated interface declarations are merged
Unlike a type, it cannot be changed after creation
// These two declarations become: // interface Point { x: number; y: number; } interface Point { x: number; } interface Point { y: number; } const point: Point = { x: 1, y: 2 };
Abstract classes
It's a mixture of interface and class: we declare abstract properties and methods that must be implemented in the derived class, like in an interface,
BUT this construct also allows writing shared logic for children. link to OOP article
Generic type
This is a dynamic
type ListResponse<T> = { count: number; next: string; previous: string; results: T[]; };
Type Guards
typeof
&instanceof
operators:
function fn(param: number | string | Date) { if (typeof param === "string") { param.slice(); } else if (param instanceof Date) { param.getTime(); } }
- Predicate
is
: Helps TypeScript better determine the type of a value that is checked by functions like isString, isUser
const isAxiosError = (error: unknown | AxiosError): error is AxiosError => { return axios.isAxiosError(error); };
in
operator: checks if field exists in object
"house" in { name: "test", house: { parts: "roof" } }; // => true "house" in { name: "test" }; // => false
Utility Types
These are like built-in "functions" for manipulating types.
For example: Partial, Pick, Omit, ReturnType, ReadOnly