Search code examples
typescripttypesinterfacemapped-types

Typescript: Mapped types with Interface


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 ?


Solution

  • 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.