Functions, Overloads and Classes
Know how TypeScript types functions (signatures, overloads, `this`, void callbacks) and classes (modifiers, abstract members, initialisation order and constructor types), and where compile-time checks stop and runtime behaviour begins.
Key points
- 1
Function types need parameter names:
(n: number) => string. Call signatures ({ (n: number): string }) also allow properties; construct signatures usenew (...) => T. - 2
A
() => voidcallback type accepts functions that return anything, but a function declared(): voidmay not return a value. - 3
Overloads are tried top to bottom and the first match wins. Callers never see the implementation signature, and a union argument needs a signature that accepts the whole union.
- 4
private,protected,readonlyandoverrideare compile-time only.#privatefields are enforced by the JavaScript runtime and can be brand-checked with#field in obj. - 5
With ES2022 targets (
useDefineForClassFields), derived fields initialise right aftersuper()and before parameter properties are assigned; redeclared fields reset base values unless you usedeclare. - 6
implementsonly checks a class against an interface. It never adds members or contextually types method parameters. - 7
Use the polymorphic
thisreturn type for fluent APIs, andabstract new (...args: any[]) => Twhen a function must accept abstract classes.
Common traps
Writing
(string) => numberdeclares a parameter namedstringof typeany.Marking callback parameters optional (
index?: number) forces every implementer to handleundefinedfor no benefit.Calling an overridable method from a base constructor runs the override before the subclass's fields are initialised.
Read the source
Further reading
Suggest a resourceTest yourself on Functions, Overloads and Classes
Ten questions, with the answer and explanation after each one.