Index Access Types in Typescript

Created: Dec 5, 2020

Last Updated: Dec 5, 2020

Somewhere along my Typescript journey I learned that you can type alias a property on an interface. This is useful if you're only concerned with a particular aspect of a type, to do, let's say, a transformation on an object of that type.

interface Address {
    line1: string
    line2: string
    city: string
    state: string

interface Person {
    name: string
    address: Address

type PersonAddress = Person["address"]

function getGeoPointsForAddress(a: PersonAddress): [number, number] {
    return [0,0];

This is valid typescript.

Indexing on a type is incredibly useful. The annoying piece of this is I had no idea where I picked it up! I searched through the Typescript Handbook and it was nowhere to be found. Even worse, I didn't know what the feature was called so googling was a little time consuming.

Of course StackOverflow came through clutch and I found my answer. It was released in version 2.1. The feature is a part of keyof and Lookup Types that included two things: an index type query (the keyof operator) and index access types (or lookup types). Index access types is the feature I was looking for.

Hopefully you find it a little easier than I did.

I'll try to get this into the handbook but contributing to open source takes much longer than just updating a blog.