TS学习之函数
Posted 枫叶布
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TS学习之函数相关的知识,希望对你有一定的参考价值。
定义函数类型(规定函数参数及函数返回值的类型,若函数没有返回值,则返回类型为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
- 默认参数(默认参数可传值也可不传,一般默认参数在必须参数之后,但也可以定义在默认参数之前,但此时必须明确传入undefined以获取默认值)
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‘ ]
以上是关于TS学习之函数的主要内容,如果未能解决你的问题,请参考以下文章