typescript ts-pattern,为什么枚举匹配不起作用?

pu82cl6c  于 2023-04-07  发布在  TypeScript
关注(0)|答案(1)|浏览(136)

我使用ts-pattern进行模式匹配。

enum PossibleSelections {
  EQUAL = 'equal',
  AVERAGE = 'average',
  LOWEST = 'lowest',
  CUSTOM = 'custom',
}

和一个选择处理程序

const handleOnSelect = (newSelection: PossibleSelections) => {
    match({ newSelection })
      .with({ newSelection: PossibleSelections.CUSTOM }, () => {
        ...do something
      })
      .with({ newSelection: PossibleSelections.AVERAGE }, () => {
        ...do something
      })
      .with({ newSelection: PossibleSelections.LOWEST }, () => {
        ...do something
      })
      .with({ newSelection: PossibleSelections.EQUAL }, () => {
        ...do something
      });
  };

但是,没有任何“做些什么”的代码运行。我已经记录了newSelection,可以看到它输出了选择。如果我选择自定义并运行console.log(newSelection, PossibleSelections.CUSTOM, typeof newSelection, typeof PossibleSelections.CUSTOM),我得到custom custom string string

qpgpyjmq

qpgpyjmq1#

由于不清楚match接受什么作为参数,我假设with表示条件,您可以尝试以下操作

enum PossibleSelections {
  EQUAL = "equal",
  AVERAGE = "average",
  LOWEST = "lowest",
  CUSTOM = "custom"
}
const str = (val: keyof typeof PossibleSelections) =>
  `do something ${val}` as const;
const handleOnSelect = (
  newSelection: keyof typeof PossibleSelections
):
  | "do something EQUAL"
  | "do something AVERAGE"
  | "do something LOWEST"
  | "do something CUSTOM"
  | null => {
  switch (newSelection) {
    case "CUSTOM": {
      return str(newSelection);
    }
    case "AVERAGE": {
      return str(newSelection);
    }
    case "EQUAL": {
      return str(newSelection);
    }
    case "LOWEST": {
      return str(newSelection);
    }
    default: {
      return null;
    }
  }
};

如果您希望通过传入键来返回值,那么可以调整str助手函数,将键直接传递给enum对象

// mapper is an array of strings
// const chunkedDocumentIds = chunkArray(mapper, 11000);
enum PossibleSelections {
  EQUAL = "equal",
  AVERAGE = "average",
  LOWEST = "lowest",
  CUSTOM = "custom"
}
const str = (val: keyof typeof PossibleSelections) =>
  `do something ${PossibleSelections[val]}` as const;
  

const handleOnSelect = (
  newSelection: keyof typeof PossibleSelections
):
  | "do something equal"
  | "do something average"
  | "do something lowest"
  | "do something custom"
  | null => {
  switch (newSelection) {
    case "CUSTOM": {
      return str(newSelection);
    }
    case "AVERAGE": {
      return str(newSelection);
    }
    case "EQUAL": {
      return str(newSelection);
    }
    case "LOWEST": {
      return str(newSelection);
    }
    default: {
      return null;
    }
  }
};

TypeScript Playground

相关问题