[Typescript] Tips: Use 'declare global' to allow types to cross module boundaries

Globals in TypeScript?! 🤯

declare global is a super useful tool for when you want to allow types to cross module boundaries. Here, we create a GlobalReducer type, where you can add new event types as you create new reducers.

types.ts:

declare global {
  interface GlobalReducerEvent {}
}

export type GlobalReducer<TState> = (
  state: TState,
  event: {
    [EventType in keyof GlobalReducerEvent]: {
      type: EventType;
    } & GlobalReducerEvent[EventType];
  }[keyof GlobalReducerEvent]
) => TState;

 

todosReducer.ts

import { GlobalReducer } from "./types";

declare global {
  interface GlobalReducerEvent {
    ADD_TODO: {
      text: string;
    };
  }
}

export const todosReducers: GlobalReducer<{ todos: { id: string }[] }> = (
  state,
  event
) => {
  
  return state;
};

 

usersReducer.ts

import { GlobalReducer } from "./types";

declare global {
  interface GlobalReducerEvent {
    LOG_IN: {};
  }
}

export const userReducer: GlobalReducer<{ id: string }> = (state, event) => {
  return state;
};

posted @ 2022-10-18 01:18  Zhentiw  阅读(146)  评论(0)    收藏  举报