2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > typescript(四)ts中函数的参数和返回值的类型定义

typescript(四)ts中函数的参数和返回值的类型定义

时间:2018-12-05 06:35:57

相关推荐

typescript(四)ts中函数的参数和返回值的类型定义

前面我们讲到过ts的静态类型定义中的函数类型定义,先来回顾下:

const fnA: () => string = () => { return '1' }const fnB: () => number = () => 6const fnC: () => boolean = () => true

拓展下:在接口中如何定义函数类型呢?接口后期会讲

interface Ifn {(one: number, two: number): number}let fniA : IfnfniA = function (one, two) {return one + two}fniA(2, 4)console.log(fniA(2, 4)) // 6

接下来我们分别学习下ts中如何对函数参数和函数返回值进行类型定义的

1.ts中函数参数的类型定义

函数的参数可能是一个,也可能是多个,有可能是一个变量,一个对象,一个函数,一个数组等等。

1.函数的参数为单个或多个单一变量的类型定义

function fntA(one, two, three) {// 参数 "two" 隐式具有 "any" 类型,但可以从用法中推断出更好的类型。return one + two + three}const aResult = fntA(1, '3', true)

修改后:

function fntA(one: number, two: string, three: boolean) {return one + two + three}const aResult1 = fntA(1, '3', true)// 如果函数的参数为单个或者多个变量的时候,只需要为这些参数进行静态类型下的基础类型定义就行

2.函数的参数为数组的类型定义

function fntB(arr) {//参数 "arr" 隐式具有 "any" 类型,但可以从用法中推断出更好的类型。return arr[0]}const bResult = fntB([1, 3, 5])

修改后:

function fntB(arr: number[]) {return arr[0]}const bResult1 = fntB([1, 3, 5])// 如果参数是数组时,只需要为这些变量进行对象类型下的数组类型定义

3.函数的参数为对象的类型定义

function fntC({ one, two }) {return one + two}const cResult = fntC({ one: 6, two: 10 })

修改后:

function fntC({ one, two }: { one: number, two: number }) {return one + two}const cResult1 = fntC({ one: 6, two: 10 })// 如果参数是对象,只需要为这些变量进行对象类型下的对象类型定义

4.函数的参数为函数的类型定义

function fntD(callback) {//参数 "callback" 隐式具有 "any" 类型,但可以从用法中推断出更好的类型callback(true)}function callback(bl: boolean): boolean {console.log(bl)return bl}const dResult = fntD(callback)

修改后:

function fntD(callback: (bl: boolean) => boolean) {callback(true)}function callback(bl: boolean): boolean {console.log(bl)return bl}const dResult = fntD(callback)// 如果参数是函数,只需要为参数进行对象类型下的函数类型定义即可

2.ts中函数返回值的类型定义

当函数有返回值时,根据返回值的类型在相应的函数位置进行静态类型定义即可

返回数字:

function getTotal2(one: number, two: number): number {return one + two;}const total2 = getTotal(1, 2);// 返回值为数字类型

返回布尔值

function getTotal2(one: number, two: number): boolean {return Boolean(one + two);}const total2 = getTotal(1, 2);// 返回值为布尔类型

返回字符串

function getTotal2(one: string, two: string): string{return Bone + two;}const total2 = getTotal('1', '2');// 返回值为字符串

返回对象

function getObj(name: string, age: number): { name: string, age: number } {return {name,age}}getObj('小红',16)// 返回值为对象

返回数组

function getArr(arr: number[]) :number[]{let newArr = [...arr]return newArr}getArr([1,2,3,4])// 返回值为数组

函数返回值为underfinde,仅仅时为了在内部实现某个功能,我们就可以给他一个类型注解void,代表没有任何返回值,

function sayName() {console.log('hello,world')}

修改后:

function sayName1(): void {console.log('无返回值')}

当函数没有返回值时

// 因为总是抛出异常,所以 error 将不会有返回值// never 类型表示永远不会有值的一种类型function error(message: string): never {throw new Error(message);}

下一篇: typescript(五)ts中数组类型的定义

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。