Type Transformations Workshop (9 exercises)
solution

Use Indexed Access Types to Extract Object Properties

The solution is to use the Indexed Access Type.

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

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

Note that you can't use dot notation to access the fields like you would a standard run-time object. This syntax is invalid:

Accessing Deeply Nested Data

Indexed access types can access deeply nested data by chaining square brackets:

Note that it doesn't matter whether you use a type or directly use indexed access types with typeof, as it all gets transformed into a type.

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.