当前位置:网站首页>Typescript type protection
Typescript type protection
2022-06-11 07:59:00 【YY little monster】
Details visible
Type protection
For union type variables , How to tell the compiler exactly what type it is
Through type assertion or type protection
let getRandomValue = ():(string | number)=>{
let num = Math.random();
return (num >= 0.5) ? 'abc' : 123.123;
}
let value = getRandomValue();
console.log(value);
// Because I don't know what type to return , Then use .length and .toFixed() Will report a mistake
if(value.length){
console.log((value as string).length);
}else{
console.log(value.toFixed());
}
Solution
1. Use type assertion
Although type assertions can tell the compiler exactly what type the current variable is ,
But every time you use it, you need to tell the compiler manually , It's a little bit of a hassle , There are many redundant codes
if((value as string).length){
console.log((value as string).length);
}else{
console.log((value as number).toFixed());
}
2. Type protection function
// Defines a type protection function , Of this function ' Return type ' Is a boolean type
// The return value type of this function is , Incoming parameter + is The specific type
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. Use typeof To implement type protection
Be careful :
If you use typeof To implement type protection , Then only use === / !==
If you use typeof To implement type protection , Then it can only protect number/string/boolean/symbol type
if(typeof value === 'string'){
console.log(value.length);
}else{
console.log(value.toFixed());
}
4. because typeof Can only protect number/string/boolean/symbol class , Objects can pass through instanceof To implement type protection
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);
}
边栏推荐
- mpi
- 2022.6.7 特长生模拟
- [poj3691] DNA repair (AC automata +dp)
- Remote office experience sharing | community essay solicitation
- C# 微信上传Form-data
- Label the mask image not obtained through labelme
- Qunhui ds918 creates m.2 SSD read / write cache
- Rabin Miller prime test
- Servlet、ServletConfig、ServletContext
- Summary of evaluation index knowledge points in target detection: summary of IOU cross overlap unit and map/ap/tp/fp/np
猜你喜欢

TiDB Cloud 上线 Google Cloud Marketplace,以全新一栈式实时 HTAP 数据库赋能全球开发者

How to start participating in the open source community

Getting started with bladed tutorial (video)

C language to achieve a simple game - minesweeping

Storage of floating point in memory

Xshell7 and xftp7 to continue using this program, you must apply the latest updates or use a new version

Figure seamless database integration tushare interface

Servlet

使用 COCO 数据集训练 YOLOv4-CSP 模型

如何开始参与开源社区
随机推荐
TypeScript-unknown类型
C language lesson 2
In an activity, view postdelay will cause memory leakage, but will not affect the life cycle execution of the activity.
Black Qunhui dsm7.0.1 physical machine installation tutorial
Login and parameterization of interface test
[the most complete ENSP [installation diagram] in history!]
Clipping and overlapping of YUV data
学习《缠解论语》
DAMENG 用户管理
A detailed explanation of one of the causes of dead loop caused by array out of bounds in C language
关于网络知识的50个问答题,你能答对几个?
[atcoder1984] wide swap
Sort - merge sort
Zero foundation self-study SQL course | union joint query
Data visualization and Matplotlib
134. 加油站
排序——交换排序
[atcoder2305] declining (game)
SylixOS SD设备驱动开发
Servlet