type annotation
A type written explicitly after a name with a colon, such as name: string, to tell the compiler what a value must be.
In more detail
Annotations are most useful on function parameters, exported functions and public interfaces, where they document the contract. Inside a function, local variables usually get their type by inference, so annotating them is redundant. Annotations are erased when the code is compiled.
Example
function sendWelcome(user: User): stringRelated terms
- type inference — The compiler working out a type from the code itself, so you do not have to write it out by hand.
- contextual typing — Type inference that flows from where a value is used, such as giving a callback's parameters the types the calling function expects.
- type erasure — The removal of all TypeScript types when code is compiled, so none of them exist while the JavaScript runs.
Taught in
- Why TypeScript: Contracts, Erased Types And Soundness — Production TypeScript
- The Compiler Pipeline: tsc, AST And Code Emission — Production TypeScript
- tsconfig.json: target, lib, strict And NodeNext — Production TypeScript
- Type Annotations, Type Inference And Contextual Typing — Production TypeScript
- Primitive Types: String, Number, Boolean, Bigint And Symbol — Production TypeScript
- Literal Types: String, Number, Boolean Literals And const — Production TypeScript
- Assertion Signatures: asserts condition And Invariants — Production TypeScript
- Why Generics: Functions, Identities And Type Variables — Production TypeScript
- Function Utilities: ReturnType, Parameters And Constructor — Production TypeScript
- ECMAScript Modules, CJS Interop And verbatimModuleSyntax — Production TypeScript
- The satisfies Operator: Safe Validation Without Widening — Production TypeScript