TypeScript:函数

本文详细介绍了TypeScript中函数的类型定义,包括指定参数和返回值类型、可选参数、默认参数以及剩余参数的用法。示例展示了如何定义和使用这些特性,帮助理解TypeScript函数类型的灵活性和强制类型检查的重要性。
摘要由CSDN通过智能技术生成

TypeScript可以为函数指定参数类型和返回类型:

function hello(who : string) : string{//"who : string"指定参数who的类型为string, ": string"指定返回值类型为string
	return "hello " + who;
}

也可以定义一个匿名函数:

let hello = function(who : string) : string{
    return "hello " + who;
}

匿名函数的完整定义如下:

let hello : (who : string) => string = function(who : string) : string{
	return "hello " + who;
}

//hello : (who:string) => string,其中"who : string"用于指定参数类型,"=> string"用于指定返回值类型

可以将函数的参数指定为可选参数,方法是在参数后面加上?, 需要说明的一点是可选参数只能放在必填参数的后面:

let hello = function(who : string, greet ?: string) : string{//greet为可选参数,不能定义在必选参数who的前面
	if(greet == undefined){//没有传递可选参数,greet的值为undefined
		greet = "hello"
	}
	return greet + " " + who;
}
console.log(hello("world"));//输出hello world
console.log(hello("world", "hi"));//输出hi world

除了可选参数,也可以为参数指定一个默认值,方法是在参数后面加上 "=默认值":

let hello = function(greet = "hello", who = "world") : string{//为参数指定默认值,当没有传递参数,或参数的值为undefined时,将参数的值设定为默认值;带有默认值的参数的位置没有限制
	return greet + " " + who;
}
console.log(hello());//没有传递参数,使用默认值,输出hello world
console.log(hello(undefined,"world"));//传递undefined, greet使用默认值,输出hello world
console.log(hello("hi", "god"));//输出hi god

可以为函数定义剩余参数,从而可以传递可变数量的参数,剩余参数会将参数保存在数组中:

let hello = function(greet, ...who : string[]) : string{//指定可选参数的类型为字符串数组, 也可以不指定类型,那么则为any[]
	return greet + " " + who;
}
console.log(hello("hi", "world", "god"));//输出hi world,god

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风静如云

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值