Beginner's TypeScript Tutorial (18 exercises)

Make a Variable Conform to an Interface

There's a little bit of syntax we need to add to our declaration to solve this problem.

By adding : User to defaultUser, we're telling TypeScript that we want it to conform to our User interface.

Now TypeScript will display errors at the line where defaultUser is declared.

We also benefit from autocompletion for the properties!

The same : Type syntax can be used with other types, including numbers and functions:

As you write TypeScript, you need to think about where you want your contracts to be, and what needs to be done in order to meet them.


The syntax right here. This little colon just before defaultUser there. What this means is if I don't parse in isAdmin, then it's going to give me an error at this line. "Property 'isAdmin' is missing in type blah blah blah but required in type 'User'." If I add that back, I can say isTrue here.

If I remove this, then nothing errors, but if I get this wrong then the error's not going to be where the actual error is. It's going to be further down in the code. And so, you need to think, when you're using TypeScript, where do I want my contracts to be? What exact thing do I want to meet to my contract?

It's so useful to have it here because, of course, the error appears in the correct place, but you also get autocomplete here, too. Without this, I don't get autocomplete on isAdmin. I've made a deliberate typo there. It's going to say, "Property 'isAdmin' is missing in type blah blah blah." I'm going to get a really confusing, big error message.

Whereas, just like this, if I say it's right there, then I get to clear it up immediately and it actually tells me exactly where the error is.

This syntax is really, really useful. You can use it for let. Let A is a number. We can say one. You can use it with const. You can use it with functions, as well. There's a lot you can do with this little syntax. It's really, really useful for making sure that your variable match a certain contract.