typescript object key type

Solutions on MaxInterview for typescript object key type by the best coders in the world

showing results for - "typescript object key type"
Miguel
29 Jul 2017
1var stuff: { [key: string]: string; } = {};
2stuff['a'] = ''; // ok
3stuff['a'] = 4;  // error
4
5// ... or, if you're using this a lot and don't want to type so much ...
6interface StringMap { [key: string]: string; }
7var stuff2: StringMap = { };
8// same as above
9
Paul
11 Jul 2017
1// For every properties K of type T, transform it to U
2function mapObject<K extends string, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U>
3
4const names = { foo: "hello", bar: "world", baz: "bye" };
5const lengths = mapObject(names, s => s.length);  // { foo: number, bar: number, baz: number }
6