Functions

Functions have type information as well. Functions are comprised of parameters and a return value:

function buildName(firstName: string, lastName: string): string {
return firstName + " " + lastName;
}

Each parameter is annotated with its type, and then the return value's type is added at the end of the function signature.

Unlike JavaScript, TypeScript enforces calls to functions to adhere to the defined signature. For example, if you try to call the function with anything other than two string parameters, the TypeScript compiler will not allow it.

You can define more flexible function signatures if you like. TypeScript supports defining optional parameters by using the question mark symbol, ?:

function buildName(firstName: string, lastName: string, title?: string): string {
return title + " " + firstName + " " + lastName;
}

const name = buildName('John', 'Doe'); // valid call

The preceding function can now be called with either 2 or 3 string parameters.

Everything in JavaScript is still supported, of course. You can still use ES6 default parameter values and rest parameters as well.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.38.253