Was this page helpful?

Typeof Type Operator

Thetypeof type operator

JavaScript already has atypeof operator you can use in anexpression context:

ts
// Prints "string"
console.log(typeof"Hello world");
Try

TypeScript adds atypeof operator you can use in atype context to refer to thetype of a variable or property:

ts
lets ="hello";
letn:typeofs;
let n: string
Try

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:

ts
typePredicate = (x:unknown)=>boolean;
typeK =ReturnType<Predicate>;
type K = boolean
Try

If we try to useReturnType on a function name, we see an instructive error:

ts
functionf() {
return {x:10,y:3 };
}
typeP =ReturnType<f>;
'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'?
Try

Remember thatvalues andtypes aren’t the same thing.To refer to thetype that thevaluef has, we usetypeof:

ts
functionf() {
return {x:10,y:3 };
}
typeP =ReturnType<typeoff>;
type P = { x: number; y: number;}
Try

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:

ts
// Meant to use = ReturnType<typeof msgbox>
letshouldContinue:typeofmsgbox("Are you sure you want to continue?");
',' expected.1005',' expected.
Try

The TypeScript docs are an open source project. Help us improve these pagesby sending a Pull Request

Contributors to this page:
OTOrta Therox  (4)
JLJimmy Liao  (1)

Last updated: Dec 16, 2025