Beginner's TypeScript Section 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.

const defaultUser: User = {}

Now TypeScript will display errors at the line w

Loading solution


0:00 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.

0:20 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?

0:40 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.

1:03 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.

1:12 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.