Reputation: 21497
When trying to use mapped types with interface, i get a weird error - which makes me think its not possible to use them together at all..
See identical type and interface declarations:
type AllWorks<T> = {
[K in keyof T]: T[K];
}
interface DoesNotWork<T> {
[K in keyof T]: T[K];
}
While first one works as expected, second one gives the TS error:
[ts] A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
[ts] Member '[K in keyof' implicitly has an 'any' type.
[ts] Cannot find name 'keyof'.
So my question is - is it even possible to map over interfaces ? if yes - then how ?
Upvotes: 8
Views: 8817
Reputation: 458
Interfaces are not built with such a purpose. You should use Type
there instead.
The Typescript compiler is telling you that you are using the wrong tool for the job :)
The most complex thing an interface can do is extend
otherwise use mapped types as a general rule.
I've built an article here about mapped types if you want to dig deeper.
Upvotes: -1