如何在TypeScript中定义具有任意数量属性的接口

时间:2017-01-18 11:27:33

标签: typescript

我想定义一个具有任意属性的接口,其类型始终相同。 E.g。

type Reducer<S, P> = (state: S, payload: P) => S

interface Reducers {
  [name: string]: Reducer
}

然后像这样使用它:

interface MyState {
  foo?: string
  bar?: string
}

const reducers: Reducers = {
  r1: (state: MyState, payload: string) => {
    return {foo: payload}
  }
}

但是我无法编译。编译器错误是:

  

错误TS2314:通用类型&#39; Reducer&#39;需要2个类型的参数。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您需要将通用参数转发到Reducers界面:

interface Reducers<S, P> {
  [name: string]: Reducer<S, P>
}

const reducers: Reducers<MyState, string> = {
  r1: (state: MyState, payload: string) => {
    return {foo: payload}
  }
}

如果编译器不允许您内联定义Reducer方法(过去我遇到了一些问题),您可以在外部定义值:

const r1Reducer: Reducer<MyState, string> = (state: MyState, payload: string) => {
    return {foo: payload}
}

const reducers: Reducers<MyState, string> = {
  r1: r1Reducer;
}

答案 1 :(得分:1)

您在代码中缺少一些泛型类型表示法。

type Reducer<S, P> = (state: S, payload: P) => S

interface Reducers<S, P> {
  [name: string]: Reducer<S, P>
}

interface MyState {
  foo?: string
  bar?: string
}

const reducers: Reducers<MyState, string> = {
  r1: (state: MyState, payload: string) => {
    return { foo: payload }
  }
}

没有它们,编译器无法确定正确类型的S和P泛型类型。