Examples covered:
Functions in TS vs. JSTypeScript:
JavaScript:
Parameter Types and Return Typesfunction CreateCustomerID(name: string, id: number): string {
return name + id;
}
Arrow Functionsconcise syntax for anonymous functions. “this” is captured at function creation - not invocation.
// normal function
let arr = allBooks.filter(function (book) {
return book.author == "john smith";
});
// arrow function
// left: parameter(s). right: function body
let arry = allBooks.filter( book => book.author === "john smith" );
Arrow Function SyntaxFunction will not accept any parameters, must add an empty set of parentheses.
myBooks.forEach( () => console.log("done reading") );
Function accept one parameter.
myBook.forEach( title => console.log(title) );
Function accept multiple parameters.
myBook.forEach( (title, idx, arr) => console.log(idx + " - " + title) );
Function accept multiple parameters and has more than one line in function body.
myBook.forEach((title, idx, arr) => {
console.log(idx + " - " + title);
// do more thing here...
});
Function TypesCombination of parameter types and return type. Variables may be declared with function types
function PublicationMessage(year: number): string {
return "Date published: " + year;
}
// this is just a type definition for a function
let publishFunc: (someYear: number) => string;
publishFunc = PublicationMessage;
// it can be written in this way
publishFunc = (year: number): string => { return "Date published: " + year };
let message: string = PublicationMessage(2017);
Optional and Default ParametersOptional parameters denoted with “?” after parameter name. Must appear after all required parameters. Default parameters may be set to a literal value or an expression.
Optional parameter
function CreateCustomer(name: string, age?: number) { }
Default parameter: literal value
function GetBookByTitle(title: string = "Learning TypeScript") { }
Default parameter: expression
function GetBookByTitle(title: string = GetMostPopularBook()) { }
Rest ParametersCollects a group of parameters into a single array.
function GetBooksReadForCust(name: string, ...bookIDs: number[]) { }
let books = GetBooksReadForCust("john", 2, 3, 5, 100);
Function OverloadsOne symbol name. Multiple function types. One implementation with type guards.
Function for author
function GetTitles(author: string): string[];
Function for available
function GetTitles(available: boolean): string[];
Function for object property
function GetTitles(bookProperty: any): string[] {
if (typeof bookProperty == "string") {
// get books by author, add to foundTitles
}
else if (typeof bookProperty == "bolean") {
// get books by availability, add to foundTitles
}
return foundTitles;
}