const user = { id: 1, name: 'Tom' }
type UserType = typeof user
// UserType = { id: number; name: string }
typeof 在 JS/TS 里有两种用法,要分清 “运行时” 和 “类型层”。
1.JS 运行时的 typeof:用来判断值的类型(返回字符串)
typeof 'hi' // 'string'
typeof 123 // 'number'
typeof true // 'boolean'
typeof {} // 'object'
typeof [] // 'object'
typeof null // 'object'(历史遗留坑)
typeof (() => {}) // 'function'
常用于 if 判断做“类型收窄”。
2.TS 类型层的 typeof:把“变量/常量的类型”拿出来
这时 typeof 不会执行,只是生成一个类型。
const user = { id: 1, name: 'Tom' }
type UserType = typeof user
// UserType = { id: number; name: string }
记忆:
- 运行时 typeof:得到 'string'/'number'... 这种字符串
- 类型层 typeof:得到一个“类型”,用来写 type X = typeof xxx