craigsnyders craigsnyders - 1 year ago 84
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'


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download