index-signature

How do I add an index signature for a mapped type?

笑着哭i 提交于 2020-12-01 02:33:22
问题 Suppose I have interface interface X { a: string; b: number; c: boolean; } and a function function values(x: X) { return Object.keys(x).map(s => x[s]) } When I enable typescript's strict flag I get the error "Element implicitly has an 'any' type because type 'X' has no index signature". So to make it explicit, I can just add an index signature to the definition of X [key: string]: any; Easy peasy. However if I X is now a mapped type instead: type X<T> = { [P in keyof T]: string; } and I have

What does a TypeScript index signature actually mean?

淺唱寂寞╮ 提交于 2019-12-19 17:34:24
问题 I've been writing TypeScript for a while and am confused about what an index signature means. For example, this code is legal: function fn(obj: { [x: string]: number }) { let n: number = obj.something; } But this code, which does basically the same thing, isn't: function fn(obj: { [x: string]: number }) { let p: { something: number } = obj; } Is this a bug? What's the intended meaning of this? 回答1: You are right to be confused. Index signatures mean a few things, and they mean slightly

What does a TypeScript index signature actually mean?

放肆的年华 提交于 2019-12-19 17:34:16
问题 I've been writing TypeScript for a while and am confused about what an index signature means. For example, this code is legal: function fn(obj: { [x: string]: number }) { let n: number = obj.something; } But this code, which does basically the same thing, isn't: function fn(obj: { [x: string]: number }) { let p: { something: number } = obj; } Is this a bug? What's the intended meaning of this? 回答1: You are right to be confused. Index signatures mean a few things, and they mean slightly