functions in TypeScript
testYourself TypeScript1266
TypeScript allows you to specify the types of the input and output values of a function.
Parameters
When you declare a function, you can add type annotations to each parameter to specify what types of parameters the function accepts.
function add(a: number, b: number) {
return a + b;}
f we try to pass more arguments that was defined in the function declaration, TypeScript will warn us that the number of arguments doesn't match the number of arguments that were expected.
console.log(add(10, 22, 6));
we get the following error:
Expected 1 arguments, but got 2.
optional parameters
The optional parameters are marked with the question mark sign that is placed at the end of the parameter name.
function get(start: number, limit: number, sortBy?: string) { }
In the given example sortBy
can be omitted because this parameter is optional.
default-initialized parameter
The default-initialized parameter will be assigned if the user does not provide any value, or if the user passes undefined
in its place.
typescript:
function add (x: number, y: number = 1): number {
return x + y;
}
console.log(add(15, undefined));
result:
16
but if we pass null
, default value won't be assigned.
typescript:
console.log(add(15, null));
result:
15
Default-initialized parameters that come after all required parameters are treated as optional, and just like optional parameters, can be omitted when calling their respective function.
function get(start: number, limit: number, query: string = "") { }
In the given example query
can be omitted because this parameter is optional.
returned value
TypeScript allows you to add a type annotation describing the value returned by the function:
function add(a: number, b: number): number {
return a + b;
}
If function doesn't return any value, you can use void
type annotation. The void
represents the absence of having any type at all.
function print(value: string): void {
console.log(value);
}
Returned type annotation is not required in TypeScript. TypeScript can figure the return type out by looking at the return statements, so we can optionally leave this off in many cases.