TypeScript Chinese documents

Definition of a function in TS

Function getInfo1 (name:string,age:number):string{return 'Student ${name} year ${age} year'} let getInfo2 = Function (name:string,age:number):string{return 'student ${name} year ${age} year'}

A complete function type in TS includes a parameter type and a return value type. If the function does not return a value, the return value of the function should be set to void.

Two optional parameters

Optional parameters must follow required parameters.

function getStudent( name:string, id? :string) :string {if(id){return 'the id of student ${name} is: ${id}'; }else{return 'student ${name} no id'; }} console.log(getStudent(' red ','wyd12d0xs2lkh')); // Student's ID is: wyd12d0xs2lkh console.log(getStudent(' Xiaogang ')); // Student Xiaogang does not have ID

Three Default Parameters

Function getFullName(firstName:string, lastName:string = 'small ') :string{firstName + lastName; } console.log(getFullName(' span ',' fine ')); // console.log(getFullName(' zhang ')); / / Zhang Xiaoming

If the default parameter precedes the required parameter, the default value will be obtained only when undefined is passed in

Function getFullName(lastName: String = 'small ',firstName: String) :string{firstName + lastName; } console.log(getFullName(' flower ',' lee ')); // console.log(getFullName(undefined,' span ')); / / Zhang Xiaoming

IV. Remaining Parameters

function sum(... result:Array<number>) :number{ console.log( result); // [1, 2, 3, 4, 5] return result.reduce((pre:number,next:number):number => { return pre + next; }); } the sum (1, 2, 3, 4, 5); / / 15

Overloading of five functions

Definition of Function Overloading: In TS, multiple functions are achieved by providing multiple function type definitions for the same function.

function setInfo(title:string):string; function setInfo(num:number):number; Function setInfo(value:any):any{if(typeof value === 'string'){return 'this is a string: ${value}'}else{return 'this is a number: ${value}` } } setInfo(10); // This is a number: 10 setInfo(' three '); // This is a string: Zhang San