Reputation: 740
In typescript, how to I write the type signature for plain old javascript object that can have any key, but the values are always strings. For example, {a:"foo"}
, {b:"bar"}
are both valid values but {a:[1,2,3]}
and {b:3}
are not.
I want to be able to write something like
let foo : {*: string} = {a: "foo"}
Currently, I am using any
to achieve this, but that isn't as precise as I would like.
Upvotes: 1
Views: 1354
Reputation: 12806
I am guessing you are looking at a enum
definition for the values of your properties.
I think you can declare it something like:
let foo: { [k: string]: 'foo' | 'bar' | 'type'};
foo.a = 'bar';
foo.d = 'type';
foo.q = 'bar';
foo.c = 'let'; // shows as not assignable
You can see it in this typescript fiddle
Upvotes: 0
Reputation: 251262
You can use an index signature to state that all values will be a string...
type Example = { [key: string]: string };
Example:
type Example = { [key: string]: string };
const a: Example = {
"anything": "any string", // ok
anotherkey: "a string", // ok
thirdKey: 1 // Error
};
Upvotes: 1