Essential Types And Notations 20 exercises

Annotating with {}

In order to annotate the user parameter as an object, we can use the curly brace syntax {}.

Let's start by annotating the user parameter as an empty object:

const concatName = (user: {}) => {
return `${user.first} ${user.last}`; // red squiggly line under `.first` and `.last`

Loading solution


00:00 Okay, we know that you can do like string like this and you can do number and all that kind of thing But how do you express objects like that? Well, we can use an object literal like this So we're literally just drawing the curly braces like this and currently this is an object literal without any properties on

00:18 You can see that we have now some errors saying property first does not exist on type empty Object here and the same with user dot last. So how do we add those properties? Well, just like we would in a JavaScript object. We just add them direct into here except for giving them some values like this

00:36 We're actually just give gonna give them some types So first is going to be a string and then last is also going to be a string And now we've got first string there and last string you notice too that it expects you to use Colons here we can use commas here if you want to but prettier if you just save the file

00:56 We'll change it back to a colon because that's what TypeScript expects So we have written our very first object type here if we for instance like misspell a property Let's say like this Then user dot last you can see property dot last does not exist on type first and this

01:12 So TypeScript is actually giving us warnings if we fail to select a property that doesn't that exists on the object So we change it back to last there's one more cool thing to show you too, which is if we were building this out Let's say we just type this out again We return user dot and then we get autocomplete based on the things that are in our object literal

01:32 So we want the first one first and then we say user dot last as the next one. Very very cool We're going to see how you can encapsulate these inside types and interfaces later But for now just object literal types on their own a super duper useful