craigsnyders craigsnyders - 1 month ago 9
TypeScript Question

Refer to a key with dot notation, type is { [x: string]: string}

How can I refer to the properties of an object where the keys can be any string?

I would expect the compiler not to throw an error on the final line:

export type apple = { [x: string]: string }

export type pie = {
fruit: apple;
}

let myPie: pie = {
fruit: {
appleVariety: 'Granny Smith'
}
}

console.log(myPie.fruit.appleVariety);

Answer

You either have an indexable object like you're using:

type apple = { [x: string]: string };
let a: apple = { appleVariety: 'Granny Smith' }
let variety = a['appleVariety'];
let something = a['something']; // no error even though it's undefined

Or specify the properties in the object:

type apple = { appleVariety: string };
let a: apple = { appleVariety: 'Granny Smith' }
let variety = a.appleVariety;
let something = a.something; // Error: Property 'something' does not exist on type '{ appleVariety: string; }'.

You can't mix the two.
The philosophy behind this is that if you know the property names then explicitly include them in your interface/type definition.
But if you just have a collection of properties in an object then the compiler won't check for the property name that is used, only the type.

Comments