微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐