Marius Schulz
Marius Schulz
Front End Engineer

Type Queries and typeof in TypeScript

TypeScript uses the typeof keyword for capturing anonymous types. Despite the same name, it is very different from JavaScript's typeof operator — in fact, the two can only appear in mutually exclusive places.

#JavaScript's typeof Operator

JavaScript has the typeof operator which returns the type of its operand as a string. As of ECMAScript 2015, typeof always returns one of seven possible string values:

typeof undefined; // "undefined"
typeof true; // "boolean"
typeof 1337; // "number"
typeof "foo"; // "string"
typeof {}; // "object"
typeof parseInt; // "function"
typeof Symbol(); // "symbol"

Because TypeScript is a strict superset of JavaScript, every valid JavaScript program is a valid TypeScript program. Therefore, the typeof operator can be used in TypeScript as well:

var numberType: string = typeof 1337;

The emitted JavaScript code is almost unchanged:

var numberType = typeof 1337;

#TypeScript's Type Queries

The typeof keyword defined in TypeScript is used to start a type query. A type query obtains the type of an identifier or property access expression (that is, multiple identifiers connected by dots):

let rectangle1 = { width: 100, height: 200 };
let rectangle2: typeof rectangle1;

Since no type annotation was provided for the rectangle1 local variable, its type is inferred to be { width: number, height: number }. We can give the same type to rectangle2 by annotating the variable declaration with the type query typeof rectangle1.

Like other artifacts of TypeScript's static type system, type queries have no runtime manifestation. They're erased from the generated JavaScript code:

var rectangle1 = { width: 100, height: 200 };
var rectangle2;

#Naming Types with Type Aliases

Using a type alias, we can give a name to the captured anonymous type and then use that name wherever TypeScript expects a type:

let rectangle1 = { width: 100, height: 200 };

// Obtain the type of `rectangle1` and call it `Rectangle`
type Rectangle = typeof rectangle1;

let rectangle2: Rectangle;

For a practical example, take a look at this strongly typed React component. It was written in TSX (TypeScript's implementation of JSX) and makes use of a type alias and a type query to obtain the type of all properties provided.