typeof运算符返回类型的定义位置及返回联合类型是否对外暴露的技术问询
typeof Questions Let's break down your two questions clearly—they're great deep dives into how TypeScript handles core language operators!
1. Where is the return type of typeof defined?
The return type behavior of typeof isn't declared in the standard lib.*.d.ts files like regular types or interfaces. Instead, it's an intrinsic (built-in) language feature that's handled directly by the TypeScript compiler itself.
You won't find a literal type definition for it in public type declaration files because its logic is baked into the compiler's type-checking engine. If you wanted to peek under the hood, you'd need to check the TypeScript source code—specifically the modules responsible for type inference and operator handling, where the possible return values of typeof are hardcoded as part of the language's specification.
2. Is the union type of typeof results exposed publicly?
Short answer: No, this union type (which is 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function') isn't exposed as a named, public type in TypeScript's standard library. That's why you didn't spot it in the lib.*.d.ts files.
That said, if you need to reuse this type in your codebase, you can easily define it yourself. Here's the straightforward, explicit way:
// Exact match of all possible typeof return values type TypeofResult = 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function';
Or if you prefer a more programmatic approach using conditional types (though the above is simpler for this use case):
type InferTypeofResult<T> = T extends string ? 'string' : T extends number ? 'number' : T extends bigint ? 'bigint' : T extends boolean ? 'boolean' : T extends symbol ? 'symbol' : T extends undefined ? 'undefined' : T extends object ? 'object' : T extends Function ? 'function' : never;
Either way, these custom types will perfectly align with the actual return values of the typeof operator in both JavaScript and TypeScript.
内容的提问来源于stack exchange,提问作者Balázs Édes

