当前位置:网站首页>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"));联合类型与重载

边栏推荐
猜你喜欢
随机推荐
WPF 使用封装的 SharpDx 控件
c语言进阶篇:自定义类型--结构体
阿里云技术专家秦隆:云上如何进行混沌工程?
win10 uwp xaml 绑定接口
PG网络传输安全SSL介绍及使用示例
Yuanguo chain game system development
JS: 数组和树的相互转换
MySQL远程备份策略举例
当前最快的实例分割模型:YOLACT 和 YOLACT++
MogDB学习笔记-环境准备及单实例安装
百度智能云重庆工业互联网平台正式亮相,深耕重庆,辐射西南
HCIP-R&S By Wakin自用笔记(1)企业网络高级解决方案
面试官:MVCC是如何实现的?
动手学深度学习_VggNet
win10 uwp win2d 离屏渲染
win10 uwp json
八一建军节 | 致敬中国人民解放军
Dragoma(DMA)元宇宙系统开发
Storage resource activation system to help new infrastructure
Regular expression is incomplete






![[Sql brush topic] Query information data--Day1](/img/a7/67b59bd41803dfc07ecb8f00669c29.png)


