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, ...

Get Hands-On Full-Stack Web Development with ASP.NET Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.