标签:ast fun 必须 argument 学习 color 箭头 erro 函数
定义函数类型(规定函数参数及函数返回值的类型,若函数没有返回值,则返回类型为null)
function add(x: number, y: number): number { return x + y }
推断类型(ts自动识别类型(按上下文归类))
function add(x: number, y: number) { return x + y } //ts会自动识别出返回类型为number
可选参数,默认参数,剩余参数
?
实现可选参数的功能,可选参数放在必填参数之后)function buildName(firstName: string, lastName?: string) { if (lastName) return firstName + " " + lastName; else return firstName; } let result1 = buildName("Bob"); // Bob let result3 = buildName("Bob", "Adams"); // Bob Adams
function buildName(firstName: string, lastName: string = "Smith") { return firstName + " " + lastName; } let result1 = buildName("Bob"); // Bob Smith let result3 = buildName("Bob", "Adams"); // Bob Adams
function buildName(firstName: string = "Mr", lastName: string ) { return firstName + " " + lastName; } let result1 = buildName("Bob","Adams"); // Bob Adams let result2 = buildName("Bob"); //error: Expected 2 arguments, but got 1. let result3 = buildName(undefined,"Smith") //Mr Smith
function buildName(firstName: string, ...restOfName: string[]) { return firstName + " " + restOfName.join(" "); } let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie"); console.log(employeeName) //Joseph Samuel Lucas MacKinzie
this和箭头函数(传统函数的this作用域是在函数调用时确定,但箭头函数的this作用域在创建时就已经确定)
let myobj = { person:["Bob","Fred","Smith"], myFn:function(){ return this.person } } let test = myobj.myFn; console.log(test()) //undefined
let myobj = { person: ["Bob", "Fred", "Smith"], myFn: function () { return () => { return this.person } } } let test = myobj.myFn(); console.log(test()) //[ ‘Bob‘, ‘Fred‘, ‘Smith‘ ]
标签:ast fun 必须 argument 学习 color 箭头 erro 函数
原文地址:http://www.cnblogs.com/sghy/p/7742785.html