- JavaScript:
typeof、instanceof、Object.prototype.toString。
typeof:返回数据的基本类型。
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof {}); // "object"
console.log(typeof []); // "object" (注意:数组也是对象)
console.log(typeof null); // "object" (历史遗留问题)
console.log(typeof undefined); // "undefined"
console.log(typeof function() {}); // "function"
instanceof:检查对象是否属于某个类的实例。
console.log([] instanceof Array); // true
console.log({} instanceof Object); // true
console.log("hello" instanceof String); // false (原始类型不是对象)
Object.prototype.toString:更精确地检查类型。
console.log(Object.prototype.toString.call([])); // "[object Array]"
console.log(Object.prototype.toString.call({})); // "[object Object]"
- TypeScript:类型断言、类型保护。
类型断言:
let value: any = "hello";
if ((value as string).length) {
console.log("It's a string!");
}
类型保护:
function isString(value: any): value is string {
return typeof value === "string";
}
if (isString(value)) {
console.log("It's a string!");
}