If you want to be able to access images.main
then you must define it explicitly:
interface Images { main: string; [key:string]: string; } function getMainImageUrl(images: Images): string { return images.main; }
You can not access indexed properties using the dot notation because typescript has no way of knowing whether or not the object has that property.
However, when you specifically define a property then the compiler knows that it’s there (or not), whether it’s optional or not and what’s the type.
Edit
You can have a helper class for map instances, something like:
class Map<T> { private items: { [key: string]: T }; public constructor() { this.items = Object.create(null); } public set(key: string, value: T): void { this.items[key] = value; } public get(key: string): T { return this.items[key]; } public remove(key: string): T { let value = this.get(key); delete this.items[key]; return value; } } function getMainImageUrl(images: Map<string>): string { return images.get("main"); }
I have something like that implemented, and I find it very useful.