Type annotations for functions – Code we add to tell Typescript what type of arguments a function will receive and what type of values it will return.
Type inference for functions – TS tries to figure out what type of value a function will return.
1 2 3 |
const add = (a: number, b: number): number => { return a + b; }; |
1 2 3 |
const subtract = (a:number, b:number): number => { return a - b; } |
Alternate forms of syntax
Annotate a by providing type number
Annotate b by providing type number
Annotate the return value by providing type number
1 2 3 4 5 6 7 |
function divide(a: number, b: number): number { return a / b; } const multiply = function(a: number, b: number) : number { return a * b; } |
if no return value, we can specify void
1 2 3 |
const logger = (message: string): void => { console.log(message); } |
TypeScript introduced a new type never, which indicates the values that will never occur.
1 2 3 4 5 6 7 8 9 10 11 |
const throwError = (message: string): never => { if (!message) throw new Error(message); return message; } // or function keepProcessing(): never { while (true) { console.log('I always does something and never ends.') } } |
Difference between never and void
ref – https://www.tutorialsteacher.com/typescript/typescript-never
The void type can have undefined or null as a value where as never cannot have any value.
1 2 |
let something: void = null; // ok let nothing: never = null; // Error: Type 'null' is not assignable to type 'never' |
A function that has return type void, and no return value, actually defaults to return undefined.
1 2 3 |
function sayHi(): void { console.log('Hi!') } |
If you you use never type, then sayHi will give a compile time error, as void is not assignable to never.
Destructuring with Annotation
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const todayWeather = { date: new Date(), weather: 'sunny' }; // parameter is forecast object // return type is void const logWeather = (forecast: { date: Date, weather: string }): void => { console.log(forecast.date); console.log(forecast.weather); } logWeather(todaysWeather); |
In order to do parameter destructuring, we do this:
1 2 3 |
const logWeather = ({ date, weather } : {date: Date, weather: string}): void => { // use date, weather as so } |
Annotation with Objects
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const profile = { name: 'alex', age: 20, coords: { lat: 0, lng: 15 }, setAge(age: number): void { this.age = age; } }; // if we want to use de-structuring, we need to write out the structure // { age: number } is the type const { age } : { age: number } = profile; //de-structure out coordinates const { coords: { lat, lng } } : { coords: { lat: number, lng: number } } = profile; |