Unions and Indexing 10 exercises
solution

Use Indexed Access Types to Extract Object Properties

The solution is to use an indexed access type.

First, extract FakeDataDefaults into its own type with help from the typeof operator:


type FakeDataDefaults = typeof fakeDataDefaults

From there, we can index each of its fields using square brackets and quotes:


export type St

Loading solution

Transcript

0:00 The solution here is to use the indexed access type. This is really cool. We've extracted FakeDataDefaults into its own type here, so String string, Int number, Float number. Then we just index into them using this syntax here.

0:17 One thing to note is that you can't do this. This is actually invalid syntax here. TypeScript gives you quite a nice warning to say FakeDataDefaults String here instead. It forces you to do this. What we end up with is imagine if we had an obj inside here and we say something like that.

0:35 We want to then access inside obj String, for instance. So type Example equals typeof FakeDataDefaults. Then access into that, grab obj, and then access into that as well. You can go actually really deep inside here and keep on chaining these.

0:54 As you can see, it doesn't matter whether you use a type here or whether you use typeof FakeDataDefaults. This gets transformed to a type anyway. It still means you can use the indexed access syntax on it.