js实现类型
JavaScript 实现类型检查的方法
JavaScript 提供了多种方式来实现类型检查,以下是一些常见的方法:
typeof 操作符
使用 typeof 操作符可以检查变量的基本类型,返回一个表示类型的字符串。例如:
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (历史遗留问题)
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"
instanceof 操作符
instanceof 用于检查对象是否为某个构造函数的实例,适用于自定义对象和内置对象:
[] instanceof Array // true
new Date() instanceof Date // true
"hello" instanceof String // false (原始类型不是对象)
new String("hello") instanceof String // true
Object.prototype.toString.call() 该方法可以更精确地识别对象的具体类型,适用于内置对象和原始类型:
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call(42) // "[object Number]"
Object.prototype.toString.call(null) // "[object Null]"
Array.isArray() 专门用于检查一个值是否为数组:
Array.isArray([]) // true
Array.isArray({}) // false
自定义类型检查函数 可以编写自定义函数实现更复杂的类型检查逻辑:
function isFunction(value) {
return typeof value === "function"
}
function isPlainObject(value) {
return value !== null && typeof value === "object" &&
Object.prototype.toString.call(value) === "[object Object]"
}
TypeScript 的类型系统
对于更严格的类型检查,可以使用 TypeScript 的静态类型系统:
接口和类型别名
interface Person {
name: string
age: number
}
type Point = {
x: number
y: number
}
类型守卫
function isString(value: any): value is string {
return typeof value === "string"
}
if (isString(input)) {
// 在此块中,input 被推断为 string 类型
}
泛型
function identity<T>(arg: T): T {
return arg
}
运行时类型验证库
对于更复杂的运行时类型检查,可以使用专门的库:
zod
import { z } from "zod"
const schema = z.object({
username: z.string(),
age: z.number().positive(),
})
schema.parse({ username: "john", age: 42 })
joi
const Joi = require("joi")
const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
age: Joi.number().integer().min(0).max(150)
})
类型转换方法
JavaScript 也提供了一些类型转换的方法:
显式类型转换
Number("42") // 42
String(42) // "42"
Boolean(1) // true
隐式类型转换
"42" + 0 // "420" (字符串拼接)
"42" - 0 // 42 (数字减法)
!!"hello" // true (双重否定转为布尔值)
这些方法可以根据不同场景选择使用,从简单的类型检查到复杂的运行时验证都能覆盖。







