Advanced Props 12 exercises
explainer

Using the Record Type to Represent an Empty Object

Let's examine a specific component. This component accepts a single property, described as config. Interestingly, config accepts an empty object type:


const Component = (props: { config: {} }) => {
return <div />
}

This type is somewhat unusual because it allows us to pass

Loading explainer

Transcript

00:00 Let's take a look at this component here. This component takes in a single prop, which is described as config. And config takes in this kind of empty object type here. But this is a very strange type because it lets me pass absolutely anything I want

00:17 into config with a couple of limits. So I can pass in anything into this object here. I'm not getting autocomplete, obviously. I can pass in literally anything. Or I can remove this entire object. I can pass in a number. I can pass in a string, and it's not going to error at me. I can even pass in a boolean or false here.

00:36 Now, the only thing that will make this error is if I pass in null or if I pass in undefined. Now, why on earth would this be happening? Well, this is actually a special type in TypeScript. And what this type says is this type represents anything with zero or more properties.

00:56 So anything that you can sort of access something on it. And this has no properties on it, but technically it could represent things that have more properties. So if you think about what a string is, a string, if I go const this is blah, blah, blah, blah, now, this has some properties on it.

01:13 So it has properties like at, charAt, symbol, and all of these different things. And you can think of this as just being something that represents everything that's not null or undefined in TypeScript. And I wanted to touch on this here because there are some exercises coming up

01:30 that you're gonna need to know about this special type in order to really get around them. Now, if we wanted to represent config as like an object without any properties, we wanted to make sure it was an object being passed, then you would pass in record string, never. Record is like a helper type here that lets us express an object.

01:50 And now we can't pass in a string here. We can't pass in a number. We can't pass in true. We have to pass in this empty object. And if we pass in anything here, then it's going to error at us because foo is not assignable to type, never. So this is the way that you actually represent empty objects.

02:07 But this type does have some use cases, but you're gonna need to know why it's slightly strange in the upcoming exercises.