【问题标题】:How to define a class with dynamic keys?如何定义具有动态键的类?
【发布时间】:2021-11-08 15:09:21
【问题描述】:

我需要使用“方法”等动态道具定义一个类。这是我写的

type Methods = {
    [name:string]:Function
}

class App <M extends Methods> { 
    [name: keyof M] : M[name] // dont work
}

var methods = {
    action : Function,
    move : Function
}

type M = keyof typeof methods;

type myApp = App<typeof methods>;

但我收到以下错误。这些可以修复吗?

索引签名参数类型不能是文字类型或泛型类型。考虑改用映射对象类型。

'name' 指的是一个值,但在这里被用作一个类型。你是说'typeof name'吗?

从导出接口返回的索引签名类型已经或正在使用私有名称'name'。

Reproducible example

【问题讨论】:

  • 什么错误?请edit您的问题包含它,不要只发布外部资源的链接。

标签: javascript typescript


【解决方案1】:

您似乎在寻找mapped types。这些仅适用于type 声明,但不适用于classes:

type App<M extends Methods> = { 
    [name in keyof M]: M[name];
}

(Full demo)

如果你真的想定义一个类,你需要用一个具体的类型来做:

var methods = {
    action: Function,
    move: Function
}
type MyApp = App<typeof methods>;

class TheApp implements MyApp {
    action!: typeof Function;
    move!: typeof Function;
    constructor() {
        Object.assign(this, methods);
    }
}

【讨论】:

  • 我不明白为什么类和接口会有这样的限制:_
猜你喜欢
  • 2020-05-04
  • 2017-12-31
  • 2017-01-08
  • 1970-01-01
  • 2020-07-15
  • 2022-12-05
  • 2015-12-22
  • 1970-01-01
  • 2018-07-04
相关资源
最近更新 更多