类型的第一个通用元素上的打字稿类型保护

Typescript typeguard on the first generic element of a type

我有一个 Actions 类型需要映射到 actionMap 变量中的一组回调。

但是,我不确定如何强制执行 Action 类型的第一个通用元素的类型。很明显,key in keyof Actions 并不能解决这个问题。我需要用什么来代替?

export interface Action<T, U> {
  type: T,
  data: U,
}

export type Actions =
  | Action<"something", {}>
  | Action<"somethingElse", {}>

const actionMap: { [key in keyof Actions]: (action: Actions) => any } = {
  // I'd like the value of the `type` property of all my actions enforced here. Ex:
  // "something": (action) => {}
  // "somethingElse": (action) => {}
}

如果我问错了问题,什么是更好的问题?我不确定我是否相应地使用了行话。

您可以通过使用索引访问类型来获取接口的 属性 并 Extract 缩小函数中 action 的类型来实现此目的。

export interface Action<T, U> {
  type: T,
  data: U,
}

export type Actions =
  | Action<"something", { something: true}>
  | Action<"somethingElse", { somethingElse: true }>

const actionMap: { [K in Actions['type']]: (action: Extract<Actions, { type: K }>) => any } = {
  "something": (action) => {}, // TS knows action.data.something exists
  "somethingElse": (action) => {} // TS knows action.data.somethingElse exists
}