当前位置:网站首页>联合类型和类型保护
联合类型和类型保护
2022-04-21 06:50:00 【小二李】
联合类型
interface Bird {
fly: boolean,
sing:()=>{}
}
interface Dog {
fly: boolean,
bark:()=>{}
}
function traingAnimal(animal: Bird | Dog) {
animal.sing() // 报错
}
联合类型只能访问到公有属性和方法。
类型保护
类型断言
如果明确知道对象类型,可以使用as转换成具体对象实例。
/// 类型保护1:类型断言
function traingAnimal(animal: Bird | Dog) {
if (animal.fly) {
(animal as Bird).sing()
} else {
(animal as Dog).bark()
}
}
in语法
如果指定属性和方法在某个实例对象中,就可以在对应语句块中调用具体实例对象的方法。
/// 类型保护2:in语法
function traingAnimal(animal: Bird | Dog) {
if ('sing' in animal) {
animal.sing()
} else {
animal.bark()
}
}
typeof 语法
/// 类型保护3:typeof 语法
function traingAnimal(first:number|string,second:number|string) {
if (typeof first === 'string' || typeof second === 'string') {
return `${first}${second}`
} else {
return first + second
}
}
instanceof 语法
instanceof 做类型判断只能识别 class 对象类型而不能识别 interface 类型。
class NumberObj {
count: number
}
// 类型保护4:instanceof 语法
function addSecond(first: object | NumberObj, second: object | NumberObj) {
if (first instanceof NumberObj && second instanceof NumberObj) {
return first.count + second.count
}
return 0
}
版权声明
本文为[小二李]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43800535/article/details/124264174
边栏推荐
猜你喜欢

sqlserver 两个表之间进行模糊查询,sqlserver 导入excel数据步骤

Usage notes of Axure product prototype tool

PLSQL developer 14 installation details

MySQL5.7安装操作手册(Centos7)

Fuzzy query between two tables of SQL server and steps of importing Excel data into SQL Server

蓝牙开源协议栈BTstack之1.0 BTstack简介

Solution to red flag with @ Autowired annotation in idea

【图像融合】基于curvelet变换实现图像融合(评价指标)含Matlab源码

Renesas ide: development environment configuration during bootloader upgrade of CS + for CC

Bluetooth Profile Specification之(AVRCP篇)5.1AVCTP的连接和释放
随机推荐
Fuzzy query between two tables of SQL server and steps of importing Excel data into SQL Server
PostgreSQL 15 即将支持SQL 标准中的 MERGE 语句
Axure产品原型工具使用笔记
Flutter初体验
Flutter 基础组件的使用
IIC bus design ① - IIC communication protocol
leetcode 209. Minimum length subarray
MySQL5.7安装操作手册(Centos7)
瑞萨IDE:CS+ for CC进行BootLoader升级时开发环境配置
[Niuke brush question 18] find the longest common substring in two strings a and B
[image fusion] image fusion based on Laplace pyramid + wavelet transform, including Matlab source code
Leetcode topic -- 120 Minimum length sum of triangles, simple DP
Dynamic generation of three-level menu
第五站孔孟之乡-----------走迷宫之最短路径
C# asp.net 调百度文字识别接口
Implementing AES encryption and decryption with PHP
Supplément à la fonction d'annotation
Postgre(pg)-SQL脚本记录
asp.net js 实现动态添加文件上传
如何修改 Rancher Server 的 IP 地址