当前位置:网站首页>TypeScript-类型保护
TypeScript-类型保护
2022-06-11 07:54:00 【YY小怪兽】
详情可见
类型保护
对于联合类型的变量,在使用时如何确切告诉编译器它是哪一种类型
通过类型断言或者类型保护
let getRandomValue = ():(string | number)=>{
let num = Math.random();
return (num >= 0.5) ? 'abc' : 123.123;
}
let value = getRandomValue();
console.log(value);
//由于不知道返回的是什么类型,则使用.length和.toFixed()会报错
if(value.length){
console.log((value as string).length);
}else{
console.log(value.toFixed());
}
解决方案
1.使用类型断言
虽然通过类型断言可以确切的告诉编译器当前的变量是什么类型,
但是每一次使用的时候都需要手动的告诉编译器, 这样比较麻烦, 冗余代码也比较多
if((value as string).length){
console.log((value as string).length);
}else{
console.log((value as number).toFixed());
}
2.类型保护函数
// 定义了一个类型保护函数, 这个函数的'返回类型'是一个布尔类型
// 这个函数的返回值类型是, 传入的参数 + is 具体类型
function isString(value:(string | number)): value is string {
return typeof value === 'string';
}
if(isString(value)){
console.log(value.length);
}else{
console.log(value.toFixed());
}
3.使用typeof来实现类型保护
注意点:
如果使用typeof来实现类型保护, 那么只能使用 === / !==
如果使用typeof来实现类型保护, 那么只能保护 number/string/boolean/symbol类型
if(typeof value === 'string'){
console.log(value.length);
}else{
console.log(value.toFixed());
}
4.由于typeof只能保护 number/string/boolean/symbol类,对象可以通过instanceof来实现类型保护
class Person {
name:string = 'lnj';
}
class Animal {
age: number = 18;
}
let getRandomObject = ():(Person | Animal)=>{
let num = Math.random();
return (num >= 0.5) ? new Person() : new Animal();
};
let obj = getRandomObject();
console.log(obj);
if(obj instanceof Person){
console.log(obj.name);
}else{
console.log(obj.age);
}
边栏推荐
- 关于网络知识的50个问答题,你能答对几个?
- 【IoT】项目管理:如何打造更好的跨职能团队?
- Lesson 1 about Xiaobai's C language
- Figure seamless database integration tushare interface
- Qunhui ds918 creates m.2 SSD read / write cache
- How to output the percent sign "%" in printf function in C language
- 如何开始参与开源社区
- Simple use of string
- Deux diplômés, la Banque a externalisé le travail d'essai pendant plus de quatre mois. Parler de vrais sentiments...
- Scrape captures 51job Recruitment Information (static page)
猜你喜欢

Understanding of Poisson distribution and Poisson process and Erlang distribution and their relations (important theories in queuing theory and operational research)

Magnifying mirror rendering

用 Keras/TensorFlow 2.9 创建深度学习模型的方法总结

Printing diamond of beginner C

二本畢業,銀行外包測試工作 4 個月有餘。聊聊一些真實感受 ...

Crawl Baidu Baipin dynamic page

(transformation) tree, binary tree and forest transformation principle

Data visualization and Matplotlib

How to find the complementary sequence of digraph

Figure seamless database integration tushare interface
随机推荐
E regression test of this featured app
Flask页面的分页
multi-sig SC
Euler's theorem and its extension (with proof)
860. 柠檬水找零
排序——归并排序
空间几何
安卓初中级开发基础知识整理(面试自用)
Using Tkinter to realize guessing numbers game
C# 微信上传Form-data
Deux diplômés, la Banque a externalisé le travail d'essai pendant plus de quatre mois. Parler de vrais sentiments...
TiDB Cloud 上线 Google Cloud Marketplace,以全新一栈式实时 HTAP 数据库赋能全球开发者
Crawl Baidu Baipin dynamic page
How to start participating in the open source community
Closure and minimum dependency in database
代码设置ConstraintLayout的layout_constraintDimensionRatio
[transfer] two-way merging and sorting of C language
远程办公经验 | 社区征文
2021-10-17
Black Qunhui dsm7.0.1 physical machine installation tutorial