Function parameters may be given type annotations with the same syntax as variable declarations – a colon next to the name. The type annotations ensure that the parameters are of the correct type.
functiongreet(noun: string){console.log(`Hello,${noun}!`);}greet('World');// Prints: Hello, Worldgreet(2020);// Argument of type 'number' is not assignable to parameter of type 'string'.
Sometimes we would like to skip providing values to function calls. We can declare some parameters in a function to be optional if a value is not provided for all arguments in a function. We do this by adding a question mark symbol,?, after the parameter name before the colon,:.
functiongreet(name?: string){console.log(`Hello,${ name||'stranger'}!`);}greet();// Prints: Hello, stranger!
If we assign a function parameter to have a default value, TypeScript will infer the parameter type to be the same as the default value’s type.
functionexponentiation(power=1){console.log(4** power);}exponentiation();// Prints: 4exponentiation(4);// Prints: 256exponentiation(true);// Error: Argument of type 'true' is not assignable to parameter of type 'number | undefined'.
By looking at the types of the values in a function’s return statement, TypeScript can infer thereturn type of a function.
functionfactOrFiction(){return Math.random()>=.5?'true':'false';}constmyAnswer: boolean=factOrFiction();// Type 'string' is not assignable to type 'boolean'
If a function does not return any value, then you can specifyvoid as a return type using type annotation.
functionsayHello():void{console.log('Hello!')}
We can be explicit about what type a function returns by adding type annotation (: followed by the type) after a function’s closing parenthesis,).
functiontrueOrFalse(value: boolean): boolean{if(value){returntrue;}return'false';// Typescript Error: Type 'string' is not assignable to type 'boolean'.}