Typescript 类型字符串不可分配给类型 keyof“Interface”

时间:2021-05-23 10:44:31

标签: typescript

我有以下代码

export interface A {
  redApple: props[];
  yellowApple: props[];
  redYellowApple: props[];

}

export type FruitColour = "red" | "yellow | "green";
export type Fruit = "apple" | "banana | "cherry";

const x = [
  "redApple",
  "yellowApple",
  "redYellowApple",
  "greenCherry"
]

export const changeFruit = (
  fruit: Fruit,
  colour: Colour
): keyof A => {
  return x
    .filter((string) => string.match(colour + fruit))
    .splice(0, 1)
    .toString();
};

我不断收到类型“字符串”不可分配给类型“keyof IndexViewDataItem”的信息。 我可以使用 myFunction(someField: keyof A | string) 但是我失去了类型保护。

任何帮助或指导将不胜感激。

1 个答案:

答案 0 :(得分:0)

设法解决了这个问题

export const changeFruit = (
  fruit: Fruit,
  colour: Colour
): keyof A => {
  const y = x
    .filter((string) => string.match(colour + fruit))
    .splice(0, 1)
    .toString();
    return y as keyof A;
};

不确定这是否仍然强制执行类型保护,但我想是的。如果没有,我仍然希望有更好的方法。