Learn TypeScript

Using `typeof` to infer a type

Using `typeof` to infer a type

In this lesson, we will learn how to use the typeof operator to infer a type from an object.

Understanding typeof in a type annotation

The syntax for using a typeof operator in a type annotation is as follows:

let newObject: typeof existingObject;

When TypeScript sees the typeof operator in a type annotation, it queries the object after it and extracts its type. So, in the example above, the type of existingObject is given to the newObject variable.

This syntax can be used on function parameters as well:

function (param: typeof existingObject) { ... }

An example

We are going to explore this approach in the code editor below:

TypeScriptOpen exercise in CodeSandbox

The editor contains a ContactDetails type which is used on a initialContactDetails variable and a parameter within a saveContactDetails function.

  • Remove the ContactDetails type alias from the code.

  • Remove the ContactDetails type annotation from the initialContactDetails variable.

🤔

What is the type of the initialContactDetails variable?

  • Remove the ContactDetails type annotation from the details parameter in the function. Replace this with a typeof annotation that references the initialContactDetails variable.
🤔

What is the type of the details function parameter?

Neat!

  • Add an additional property to initialContactDetails:
const initialContactDetails = {
...
mobile: ""
};
🤔

What is the type of the details function parameter now?

Cool!

Summary

The typeof type annotation can be used to extract the type from an object. This approach reduces the types we need to create, making our code more maintainable.

Next up is a quiz to test our knowledge of mapped types.

Did you find this lesson useful?

Share this lesson on twitter
© 2023 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more