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:
The editor contains a ContactDetails type which is used on a initialContactDetails variable and a parameter within a saveContactDetails function.
Remove the
ContactDetailstype alias from the code.Remove the
ContactDetailstype annotation from theinitialContactDetailsvariable.
What is the type of the initialContactDetails variable?
- Remove the 
ContactDetailstype annotation from thedetailsparameter in the function. Replace this with atypeofannotation that references theinitialContactDetailsvariable. 
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.
