Create Type From Any Given Data in TypeScript

Kamran Ahmed
InstructorKamran Ahmed
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

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.

egghead
egghead
~ 11 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today