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?
So far in TypeScript (as of version 2.7.2), union type signatures in interfaces are not allowed and instead mapped types should be used (as you correctly have).
Docs .
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.