The typeof operator
The typeof
operator is commonly used in JavaScript to determine a value's data type when a program is running (i.e. at runtime). TypeScript also allows you to use typeof
to retrieve the type of a value at compile time.
This is especially useful when we want to retrieve the return type of a function.
Notice that we cannot use the function name f
as a type, since f
is a value.
If you examine the JavaScript that is generated from this program, the name compileType
is nowhere to be found - it is a type construct that only exists for the sake of the compiler. Just as we can extract some basic type information for f
at runtime with typeof f
, we can use the same expression typeof f
to extract detailed type information from the TypeScript compiler.
Limitations
TypeScript intentionally limits the expressions that you can use typeof
on.
Specifically, you can only use typeof
on variable names or their properties.