【问题标题】:Dynamic interfaces with generics带有泛型的动态接口
【发布时间】:2018-01-14 07:16:25
【问题描述】:

我在这里简化问题。

interface Identity{
    name: string;
}

另一个通用接口

interface State<T extends Identity>{
    [T.name] : StateContainer<T>
}

但这不会起作用,因为它会给出错误

找不到T

如果我尝试通过将其保存在函数中来生成它

function generate(c : Identity){
    interface State<T>{
        [c.name]: StateContainer<T>
    }
}

上面写着

接口中的计算属性名称必须直接引用内置符号。

我想要的输出是具有动态界面,例如 . State&lt;Tenant&gt; 应该表现得很好

interface State{
    'tenant': ....
}

【问题讨论】:

  • 你想达到什么目的?我在这里有点打字稿方面,因为我也不懂你的代码
  • 我实际上是在尝试使用泛型来概括代码,我更新了我的预期输出
  • Tenant类型和'tenant'字符串有什么联系?后者应该从哪里检索?
  • 它可以从Identity 扩展,并在Tenant 内有一个name 属性或者...每个函数都有name 属性,所以我可以直接调用Tenant.name

标签: typescript typescript-generics


【解决方案1】:

你可以使用mapped types:

type State<T extends Identity> = {
    [P in keyof T] : StateContainer<T>
}

【讨论】:

  • 它给出错误:A computed property name must be of type 'string', 'number', 'symbol', or 'any'. Cannot find name 'keyof'. 你试过了吗?
  • 这是example
  • 但是从您更新的示例来看,您似乎想要Identity.name 的运行时值中的属性名称。我认为这不会起作用,因为接口仅在编译时可用。
猜你喜欢
  • 1970-01-01
  • 2016-12-14
  • 1970-01-01
  • 2021-10-03
  • 2020-03-24
  • 2023-03-31
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
相关资源
最近更新 更多