当前位置:网站首页>03 ts类型缩小,函数
03 ts类型缩小,函数
2022-08-04 19:11:00 【是云呀!】
类型缩小
在开发中,我们可以增加判断等,来确定某个值到底是什么类型,来缩小他的值范围
而我们编写的判断语句称为类型保护
常见类型保护: typeof 平等缩小(=== == !== != switch) instanceof in 等等
进行类型缩小后,ts的代码提示更好
// typeof
function typeofFun(message: number|string) {
if (typeof message === "string") {
console.log(message.length);
} else {
console.log(message);
}
}
函数类型
在js中函数作为一等公民,使用函数过程中,函数也有自己的类型,编写函数类型表达式,表示函数类型
function useFun(fn: (num1: number,num2: number) => number) {
console.log(fn(10, 20));
}
function fun(num1: number, num2: number): number {
return num1 + num2
}
useFun(fun)
// 函数赋值给变量
type Fun222 = (num1: number, num2: number) => number
const fun222: Fun222 = (num1: number, num2: number) => {
return num1*num2
}
useFun(fun222)
函数参数可选类型
// 可选类型必须写后面
function funx(x: number, y?: number) {
console.log(x,y);
}
funx(20)
参数默认值
// 带默认参数的话最好写后面,写前面的话,funy(undefined,10)这样调用
function funy(x: number, y: number = 6) {
console.log(x+y);
}
funy(20)
剩余参数
将不定量参数放到数组中
function sum(...nums: number[]){
console.log(nums);
}
sum(20,30)
sum(20,30,80)
函数中this的默认推导
// ts认为函数eating有一个对应的this的外部对象info,所以在使用时,把this当做该对象,
// 我们不需要其他操作
const info = {
name: "shi yun ya",
eating: function() {
console.log(this.name);
}
}
info.eating()
不明确this类型
// eating可以被任意调用,ts是推导不到this指向谁,所以要明确this,第一个参数明确this.其他参数往后写
type ThisType = {
name: string
}
function eating(this: ThisType) {
console.log(this.name);
}
const info = {
name: "shi yun ya",
eating: eating
}
info.eating()
函数的重载
// 需求number类型或string类型相加
// 这样写不行,报错string与number联合类型不能+
// function sum(a: number|string, b: number|string ){
// return a+b
// }
// 写多个同名函数,会根据参数类型来执行函数体
function sum(a: number, b: number): number
function sum(a: string, b: string): string
function sum(a: any, b: any): any {
return a+b
}
// 有实现体的函数不能被调用
console.log(sum(2,3));
console.log(sum("22","444"));
联合类型与重载
边栏推荐
猜你喜欢
随机推荐
Scala105-Spark.sql中collect_list用法
直播回顾|7 月 Pulsar 中文开发者与用户组会议
PG网络传输安全SSL介绍及使用示例
译文推荐|Apache Pulsar 隔离系列(四):单集群隔离策略
The CPU suddenly soars and the system responds slowly, what is the cause?Is there any way to check?
VPC2187/8 电流模式 PWM 控制器 4-100VIN 超宽压启动、高度集成电源控制芯片推荐
[Distributed Advanced] Let's fill in those pits in Redis distributed locks.
如何进行自动化测试?【Eolink分享】
查询APP Store已发布过的版本记录
在表格数据集上训练变分自编码器 (VAE)示例
在线生成接口文档
CIFAR发布《AI伦理的文化:研讨会报告》【附下载】
如何给MySQL添加自定义语法 ?
internship:改了需求
MMDetection 使用示例:从入门到出门
方法的重写
Switch node version and switch npm source tool
测试工程师如何突破职业瓶颈?
win10 uwp MetroLog 入门
存储资源盘活系统助力新基建