重新选择 redux 存储的 createSelector 类型定义

reselect createSelector type definitions for a redux store

我的 redux reducer 有以下状态类型:

export interface CharactersState {
  characters: CharacterType[];
  error: string | null;
  isFetching: boolean;
}

然后我将此状态类型与 combineReducer 一起使用来创建我的商店:

const initialState: CharactersState = {
  characters: [],
  error: null,
  isFetching: true // initiated with fetching true on app load
};

const characters = (state = initialState, action: CharacterActionsType) => {
  switch (action.type) {
   // commented out reducer logic here since it is not relevant
   //...

    default:
      return state;
  }
};

const rootReducer = combineReducers({
  characters
});

export type RootStateType = ReturnType<typeof rootReducer>;
export default rootReducer;

然后我在组件控制器中使用这个 rootReducer:

const getCharacters = (state: RootStateType): CharactersState =>
  state.characters;

export const makeCharactersList = createSelector<
  RootStateType,
  CharactersState,
  CharacterListType[]
>(getCharacters, characters => {
  return characters.characters
    .map(character => {
      return {
        _id: character._id,
        name: character.name,
        description: character.description
      };
    })
    .sort((a, b) => {
      return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
    });
});

const mapStateToProps = (state: RootStateType) => {
  return {
    characters: makeCharactersList(state)
  };
};

const mapDispatchToProps = (dispatch: any) => {
  return {
    handleDeleteClick: (_id: string | null) => {
      dispatch(postDeleteCharacter(_id));
    }
  };
};

const connector = connect(mapStateToProps, mapDispatchToProps);
export type PropsFromRedux = ConnectedProps<typeof connector>;

export default connector(CharacterSidebar);

控制器在父组件中渲染,没有传递任何道具:

<Sidebar />

如何为 makeCharactersList 编写正确的类型定义? createSelector 似乎应该采用 State、OwnProps、ConnectedProps 的类型——在我的例子中,OwnProps 似乎只是一个空对象?

但是当我将类型定义设置为:

createSelector<
  RootStateType,
 {},
  CharacterListType[]

我收到以下错误:

Property 'characters' does not exist on type '{}'.

createSelector 有多个重载,但您要匹配的重载是:

export function createSelector<S, R1, T>(
  selector: (state: S) => R,
  combiner: (res: R1) => T,
): OutputSelector<S, T, (res: R1) => T>;

三个仿制药是:

  1. S - 根状态的类型 - RootStateType
  2. R1 - 第一个选择器选择的值,也是组合器的输入 - CharactersState
  3. T - 您从组合器中 return 的值 - Pick<CharacterType, '_id' | 'name' | 'description'>[](仅具有选定属性的字符数组)

可能您的 CharacterListType 是 #3 中所选属性的别名?如果是这样,那么您的代码块中的它是正确的。

export const makeCharactersList = createSelector<
  RootStateType,
  CharactersState,
  CharacterListType[]
>(getCharacters, characters => {
...