重庆熊猫 Loading

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
posted @ 2022-06-30 23:39  重庆熊猫  阅读(301)  评论(0编辑  收藏  举报