HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptCritical

Enforcing the type of the indexed members of a Typescript object?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescriptobjecttheenforcingmemberstypeindexed

Problem

I would like to store a mapping of string -> string in a Typescript object, and enforce that all of the values map to strings. For example:

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


Is there a way for me to enforce that the values must be strings (or whatever type..)?

Solution

var stuff: { [key: string]: string; } = {};
stuff['a'] = ''; // ok
stuff['a'] = 4;  // error

// ... or, if you're using this a lot and don't want to type so much ...
interface StringMap { [key: string]: string; }
var stuff2: StringMap = { };
// same as above

Code Snippets

var stuff: { [key: string]: string; } = {};
stuff['a'] = ''; // ok
stuff['a'] = 4;  // error

// ... or, if you're using this a lot and don't want to type so much ...
interface StringMap { [key: string]: string; }
var stuff2: StringMap = { };
// same as above

Context

Stack Overflow Q#13315131, score: 1185

Revisions (0)

No revisions yet.