Typeof Type Operator
Thetypeof type operator
JavaScript already has atypeof operator you can use in anexpression context:
tsTry// Prints "string"console .log (typeof"Hello world");
TypeScript adds atypeof operator you can use in atype context to refer to thetype of a variable or property:
tsTrylets ="hello";letn :typeofs ;
This isn’t very useful for basic types, but combined with other type operators, you can usetypeof to conveniently express many patterns.For an example, let’s start by looking at the predefined typeReturnType<T>.It takes afunction type and produces its return type:
tsTrytypePredicate = (x :unknown)=>boolean;typeK =ReturnType <Predicate >;
If we try to useReturnType on a function name, we see an instructive error:
tsTryfunctionf () {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 thatvalues andtypes aren’t the same thing.To refer to thetype that thevaluef has, we usetypeof:
tsTryfunctionf () {return {x :10,y :3 };}typeP =ReturnType <typeoff >;
Limitations
TypeScript intentionally limits the sorts of expressions you can usetypeof on.
Specifically, it’s only legal to usetypeof 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:
tsTry// Meant to use = ReturnType<typeof msgbox>let',' expected.1005',' expected.shouldContinue :typeofmsgbox ( "Are you sure you want to continue?");
The TypeScript docs are an open source project. Help us improve these pagesby sending a Pull Request ❤
Last updated: Dec 16, 2025