Typescript中的数据类型检测

更新记录
2022年6月30日 发布。

和JavaScript类似,使用typeof和instanceof关键字即可。

typeof#

用于检测变量的类型,只支持两种语法:

typeof  v  ===  "typename"
typeof  v  !==  "typename"

"typename"必须是 "number","string","boolean"或 "symbol"。

let test1: number & string & boolean = <number & string & boolean> 1;
let test2: string = 'abc';
console.log(typeof test1  === "string"); //false
console.log(typeof test2  === "string"); //true

instanceof#

instanceof用于检测实例的类型。
instanceof的右侧要求是一个构造函数。

class testClass1
{
}

class testClass2 implements testClass1
{
}

let a:testClass1 = new testClass2();

console.log(a instanceof testClass1); //false
console.log(a instanceof testClass2); //true

作者:重庆熊猫

出处:https://www.cnblogs.com/cqpanda/p/16260089.html

版权:本作品采用「不论是否商业使用都不允许转载,否则按3元1字进行收取费用」许可协议进行许可。

posted @   重庆熊猫  阅读(305)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示