0

我有一个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) => {}
}

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

4

1 回答 1

0

您可以通过使用索引访问类型来获取接口的属性,并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
}
于 2020-11-19T03:50:06.377 回答