简体   繁体   English

Typescript 2.0.x与2.1.x,类型定义由switch / case语句过滤

[英]typescript 2.0.x vs. 2.1.x, type definition filtered by switch/case statement

@ngrx/store (an observable redux implementation for angular (2) ) uses this pattern to get the proper type to a reducer @ ngrx / store (angular(2)的可观察到的redux实现)使用此模式将适当的类型传递给reducer

See the actual code 查看实际代码

export const ActionTypes = {
  FOO:  type('foo'),
  BAR:  type('bar')
};

export class FooAction implements Action {
  type = ActionTypes.FOO;

  constructor(public payload: string) { }
}

export class BarAction implements Action {
  type = ActionTypes.BAR;

  constructor(public payload: number) { }
}

export type Actions
  = Foo
  | Bar;

along with a reducer: 以及减速器:

export class SomeReducerState {
  foo: string;
  bar: number;
}

const initialState = {
  foo: undefined,
  bar: 0
};

export function someReducer(
  state: SomeReducerState = initialState,
  action: some.Actions
): SomeReducerState {

  switch (action.type) {
    case some.ActionTypes.FOO:
      return Object.assign({}, state, { foo: action.payload });
    case some.ActionTypes.BAR:
      return Object.assign({}, state, { bar: action.payload });
    default:
      return state;
  }

}

The way it worked in typescript 2.0.x was that(I think) it would use the switch/case to decide/filter out what's the proper type for action.payload , so inside case some.ActionTypes.FOO action.payload was string , inside BAR it was number . 它在typescript 2.0.x中的工作方式是(我认为)它将使用switch / case来决定/过滤出什么是action.payload的正确类型,因此在case some.ActionTypes.FOO action.payloadstring ,在BAR里面是number Now with typescript 2.1.x it seems to be any . 现在,随着打字稿的2.1.x它似乎是any Is there any way to achieve the same results with 2.1.x? 有什么方法可以用2.1.x达到相同的结果? is that a bug? 那是个错误吗?

The way to do it is by using readonly on type . 做到这一点的方法是对type使用readonly Another benefit is that it won't require the type utility function to coerce the type of the strings anymore. 另一个好处是它不再需要type实用程序函数来强制转换字符串的类型。

Full code here . 完整代码在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM