【问题标题】:Typescript generics - use interfaces keys for another key type打字稿泛型 - 将接口键用于另一种键类型
【发布时间】:2021-01-03 16:05:56
【问题描述】:

很难解释我想要达到的目标(不确定是否可能)所以这里是代码:

interface CellConfig {
  btn?: cellBtn;
  ...
}
interface CellBtn {
  isEnabled?: boolean;
  label?: string;
  style?: any;
  classes?: any;
}
interface DataSet {
  position: number;
  name: string;
  weight: string;
  symbol: string;
  config?: *missing part, not sure how to do it*
}

所以我想要这样的东西:

let dataSet: DataSet = {
  position: 1,
  name: 'test',
  weight: '11',
  symbol: '123',
  config: { position: { btn: {isEnabled: true }}, name: { btn: { isEnabled: true }}}
}

基本上,config 应该是可选对象,并且只允许使用 DataSet 键(config 除外),并且 config 对象中的每个键都应该是 CellConfig 类型

【问题讨论】:

  • 这个问题好像和generics没什么关系。

标签: javascript typescript typescript-typings typescript-generics


【解决方案1】:

为了便于构造DataSet,我可能会将接口拆分为非config 属性,如下所示:

interface BaseDataSet {
    position: number;
    name: string;
    weight: string;
    symbol: string;
}

然后让DataSet 使用mapped config 属性对其进行扩展:

interface DataSet extends BaseDataSet {
    config?: { [K in keyof BaseDataSet]?: CellConfig }
}

您可以验证其行为是否符合您的示例的预期。

Playground link to code

【讨论】:

    【解决方案2】:

    这是@jcalz 回答的一种更复杂的方式,避免了创建新类型(尽管以可读性为代价)

    由于您使用的是interfaces,因此您可以使用this 访问完整类型,然后使用Exclude<keyof this, "config"> 排除config 以获取无config 的类型,创建CellConfigs 的对象使用Record<keyof Exclude<keyof this, "config">, CellConfig> 并使用Partial<Record<Exclude<keyof this, "config">, CellConfig>> 将所有选项设为可选:

    interface DataSet {
      position: number;
      name: string;
      weight: string;
      symbol: string;
      config?: Partial<Record<Exclude<keyof this, "config">, CellConfig>>;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 2018-12-27
      • 2020-08-31
      • 2021-04-18
      • 1970-01-01
      相关资源
      最近更新 更多