打字稿中的可选索引签名

时间:2019-03-05 21:42:07

标签: typescript

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

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>
}

但这不是有效的打字稿。

我想做的是可能的吗?

1 个答案:

答案 0 :(得分:1)

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

[ratings]

用法:

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

TypeScript Playground

相关问题