【问题标题】:optional index signature in typescript打字稿中的可选索引签名
【发布时间】:2019-03-06 06:33:42
【问题描述】:

我希望能够采用这样的类型:

export interface NodesState {
  attr1: number;
  attr2: number;
  attr3: number;
}

并赋予用户命名类型的能力。

所以这是合法的:

{
  namespace1: {
    attr1: 100,
    attr2: 150,
    attr3: 200
  },
  namespace2: {
    attr1: 300,
    attr2: 400
  }
}

但是没有命名空间也是合法的:

{
  attr1: 200,
  attr2: 100,
  attr3: 200
}

我试过了:

export type MakeState<T> = T & {
  [key: string]?: Partial<T>
}

但这不是有效的打字稿。

我正在尝试做的事情可能吗?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    如果我理解正确,那就是你要找的东西:

    type MakeState<T> = T & { [index: string]: T }
    

    用法:

    declare const state: MakeState<NodesState>;
    
    state.attr1;       // `number`
    state["foo"]       // `NodesState`
    

    TypeScript Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-19
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      • 2021-03-06
      相关资源
      最近更新 更多