How can I enforce the type of the values in a TypeScript object with string keys?

How can I enforce the type of the values in a TypeScript object with string keys? I want to create a TypeScript object that stores a mapping of string → string, ensuring that all values associated with the string keys are of type string.

For example:

var stuff = {};
stuff["a"] = "foo";   // okay
stuff["b"] = "bar";   // okay
stuff["c"] = false;   // ERROR!  bool != string

Is there a way to enforce that the values in this object must always be strings (or another specific type)?

Hi,

You can define a type for your object where the values are constrained to a specific type, such as string. For example:

type StringMap = {
    [key: string]: string;
};

const stuff: StringMap = {};
stuff["a"] = "foo";   // okay
stuff["b"] = "bar";   // okay
stuff["c"] = false;  // ERROR: Type 'boolean' is not assignable to type 'string'

This approach ensures that any value assigned to stuff must be a string.

Define a class with methods to add properties while enforcing the type of the values:

class StringMap {
    private map: { [key: string]: string } = {};

    set(key: string, value: string): void {
        this.map[key] = value;
    }

    get(key: string): string | undefined {
        return this.map[key];
    }
}

const stuff = new StringMap();
stuff.set("a", "foo");   // okay
stuff.set("b", "bar");   // okay
// stuff.set("c", false);  // ERROR: Argument of type 'boolean' is not assignable to parameter of type 'string'

Using a class allows you to enforce type safety at runtime and provides encapsulation.

You can define an interface with an index signature and then use it to type-check your object:

interface StringMap {
    [key: string]: string;
}

const stuff: StringMap = {} as StringMap;
stuff["a"] = "foo";   // okay
stuff["b"] = "bar";   // okay
// stuff["c"] = false;  // ERROR: Type 'boolean' is not assignable to type 'string'

This approach provides a flexible way to enforce type constraints while allowing you to add or modify the object as needed.