3

考虑以下代码:

interface FooBarTypeMap {
  FOO: FooInterface;
  BAR: BarInterface;
}

type FooBarTypes = "FOO" | "BAR";

export interface FooBarAction<T extends FooBarTypes> {
  type: T;
  data: FooBarTypeMap[T];
}

const doSomthingBasedOnType = (action: FooBarAction<FooBarTypes>): void => {
  switch (action.type) {
    case "FOO":
      FooAction((action as FooBarAction<"FOO">));
  }
};

const FooAction = (action: FooBarAction<"FOO">): void => {
  //do something with action.data
};

现在,我想避免在 doSomthingBasedOnType 中看到的强制转换(作为 FooBarAction<"FOO"> 的操作),因为如果接口使其成为此开关内的唯一可能性,则作为定义。我可以在我的代码中更改某些内容以使其正常工作,还是这只是 TypeScript 中的错误?

4

1 回答 1

2

你需要转变FooBarAction为一个有区别的工会。目前你的版本FooBarAction不是很严格,while typemust be one "FOO" | "BAR"and datamust be one ofFooBarTypeMap[FooBarTypes] = FooInterface | BarInterface两者之间没有关系。所以这可以被允许:

let o : FooBarAction2<FooBarTypes> = {
  type: "BAR",
  data: {} as FooInterface
}

有区别的联合版本如下所示:

export type FooBarAction = {
  type: "FOO";
  data: FooInterface;
} | {
  type: "BAR";
  data: BarInterface;
}

const doSomthingBasedOnType = (action: FooBarAction): void => {
  switch (action.type) {
    case "FOO":
      FooAction(action);
  }
};

// We use extract to get a specific type from the union
const FooAction = (action: Extract<FooBarAction, { type: "FOO" }>): void => {
  //do something with action.data
};

您还可以使用条件类型的分配行为从类型联合创建联合:

interface FooInterface { foo: number}
interface BarInterface { bar: number}
interface FooBarTypeMap {
  FOO: FooInterface;
  BAR: BarInterface;
}

type FooBarTypes = "FOO" | "BAR";

export type FooBarAction<T extends FooBarTypes> = T extends any ? {
  type: T;
  data: FooBarTypeMap[T];
}: never;


const doSomthingBasedOnType = (action: FooBarAction<FooBarTypes>): void => {
  switch (action.type) {
    case "FOO":
      FooAction(action);
  }
};

const FooAction = (action: FooBarAction<"FOO">): void => {
  //do something with action.data
};
于 2018-11-20T12:04:34.010 回答