The typeof
type operator
JavaScript already has a typeof
operator you can use in an expression context:
// Prints "string"console .log (typeof "Hello world");
TypeScript adds a typeof
operator you can use in a type context to refer to the type of a variable or property:
lets = "hello";letlet n: stringn : typeofs ;
This isn’t very useful for basic types, but combined with other type operators, you can use typeof
to conveniently express many patterns. For an example, let’s start by looking at the predefined type ReturnType<T>
. It takes a function type and produces its return type:
typePredicate = (x : unknown) => boolean;typetype K = booleanK =ReturnType <Predicate >;
If we try to use ReturnType
on a function name, we see an instructive error:
functionf () {return {x : 10,y : 3 };}type'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?2749'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?P =ReturnType <>; f
Remember that values and types aren’t the same thing. To refer to the type that the value f
has, we use typeof
:
functionf () {return {x : 10,y : 3 };}typetype P = {P =ReturnType <typeoff >;x: number;
y: number;
}
Limitations
TypeScript intentionally limits the sorts of expressions you can use typeof
on.
Specifically, it’s only legal to use typeof
on identifiers (i.e. variable names) or their properties. This helps avoid the confusing trap of writing code you think is executing, but isn’t:
// Meant to use = ReturnType<typeof msgbox>let',' expected.1005',' expected.shouldContinue : typeofmsgbox ( "Are you sure you want to continue?");