Transcript from the "Indexed Access Types" Lesson
>> Let's talk about Indexed Access Types. The concept here is we're going to grab a piece of type information from another type using something that feels like a property key. So let's imagine we have an interface called Car, we can grab just the type of the color property here.
[00:00:28] Using, it kind of looks like the square bracket access notation for taking something off of a dictionary or accessing an element of an array. Note that although when working with values using the square brackets, we know that we can use .notation, right? So if we have a dictionary, and we saw this we probably say, well why don't you just doing like car.color?
[00:00:56] That will not work here, this must be using square brackets. And you have to pass a string literal type into it. So there is some enforcement of a constraint here, so color is present on key of car. But look what happens if we use something that's not on car.
[00:01:20] So you'll get an error message. There is some validations helps catch spelling errors or if you were to remove something from car you think it's unused, then have confidence that all of these index access types will light up. And of course you can repeat this pattern, right? So if we only wanted to have the red part of car color, we could say give me color, and then within that just grab read.
[00:01:52] And so you could see these boxes, these square brackets applied over and over. Interestingly, if we pass a union type through this indexed access type, we get a union type out. So year is a number, color is red, green, and blue on an object. So you can see here it's, I call this projecting, right, you can almost sort of send your union type of keys into this index access type.
[00:02:27] And you get arguing union type of types of the values instead of types of the keys. Pretty straightforward concept, it's just sort of accessing a piece by name. And I know I use similar language to describe, extract, and exclude. Hopefully you can see the difference between what we're looking at here which is grabbing a chunk of an object type as is.
[00:02:54] As opposed to the conditional type with the infer keyword, where we were grabbing the constructor or looking at the construct signature, plugging up the argument out of that. That's a much more heavy handed way to do things behind the scenes it's also much more expensive to do things that way.
[00:03:12] This is cheap, this will not really affect your performance. Okay, last big concept and it's a big one, this is like a triple size section here, it's mapped types. So let's take a look at that.