Create Type From Any Given Data in TypeScript

Kamran Ahmed
InstructorKamran Ahmed
Share this video with your friends

Social Share Links

Send Tweet

TypeScript can infer the type of a variable by looking at the data assigned to it. It also allows you to create a reusable type that it has inferred and later reuse it in your application. In this lesson, we look at the typeof operator and see how we can use it to create reusable types from data.

Kamran Ahmed: [0:00] We have a user object here with the name set to John Doe and age is set to 27. We don't have the type assigned to this variable. If I hover over the user variable, you will be able to see that type [inaudible] are able to infer the type of object and assign it the name of string and age of number.

[0:17] Let's say that we want to create a new user object. If I put const user2, and if I try to get the autocompletion here, you will see that we are not getting the name and the age here because this user2 has nothing to do with this user. We don't have the type assigned to it, so we're not getting the autocompletion.

[0:35] Let's say that we want to get the type of this user object in that separate type so that we can reuse it in the future. For that, I can do type user is type of user.

[0:47] Now, if I hover over the user type, you will see that it has a name string and age number, which we infer from the user object. If I put here the user and if I type again the autocompletion here, you will see that we are getting the name and age.

[1:02] Let's say I put age 28 and name is Jane Doe. If I print to the console user2, you will see that we have a second object with the properties name and age.