A TypeScript type annotation states what values a parameter, variable, or function result is expected to accept. Write it after a colon: `param: number`. The compiler can then reject a string passed to that parameter before the code runs. An annotation changes checking, not JavaScript behavior: it is removed when TypeScript compiles to JavaScript. section 3.4.2
Choose an annotation that expresses the values the code needs:
- `any` permits values of any type. Use it when that freedom is intentional, rather than to bypass a useful compiler error. section 3.4.2
- `string | null` accepts either value; `string | undefined` does not also accept `null`. TypeScript can infer a variable’s type from its initial value, but an explicit union is needed when later assignments require other types. section 3.4.6 section 4.2
- Put a return annotation after a function’s parameter list, as in `function composeString(val: string): string`. TypeScript checks the returned result against it. section 4.2.4
- For an array containing several permitted types, write `(number | string | boolean)[]`. The parentheses make the union apply to each item, not to the array as one alternative. section 4.3
A union can require more work inside a function. With `param: number | string`, TypeScript rejects `param.toFixed(2)` until a `typeof` check establishes that `param` is a number. It can also reject `param + 100` because the operation is ambiguous for the union. Casts to `any` can suppress such checks, but do not resolve the underlying uncertainty. section 3.4.2
Listing 3.21. Checking a type in the main.ts file in the src folder
function myFunction(param: number | string) {
if (typeof(param) == "number") {
let numberResult = param.toFixed(2);
console.log("My result: " + numberResult);
} else {
let stringResult = param + 100;
console.log("My result: " + stringResult);
}
}
myFunction(1);
myFunction("London");
The `typeof` branches let the number branch call `toFixed(2)` while handling the string branch separately. section 3.4.2
Do not treat annotations as runtime validation. When an Angular pipe receives values from a template, its `transform` method may need to parse or convert them even if its parameters and result have TypeScript annotations. section 17.3
















