打字稿:带接口的映射类型

c69*_*c69 4 types interface typescript mapped-types

当尝试将映射类型与接口一起使用时,我收到一个奇怪的错误 - 这让我认为根本不可能将它们一起使用..

请参阅相同的类型和接口声明:

type AllWorks<T> = {
    [K in keyof T]: T[K];
}

interface DoesNotWork<T> {
    [K in keyof T]: T[K];
}
Run Code Online (Sandbox Code Playgroud)

虽然第一个按预期工作,但第二个给出了 TS 错误:

[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'.
Run Code Online (Sandbox Code Playgroud)

所以我的问题是 -甚至可以映射接口吗?如果是 - 那么如何?

Beh*_*ooz 6

到目前为止,在 TypeScript 中(从 2.7.2 版开始),接口中的联合类型签名是不允许的,而应该使用映射类型(正如您正确的那样)。

文档