ts模式,为什么enum匹配不工作?



我使用ts-pattern进行模式匹配。我有一个enum

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,可以看到它输出了选择。如果我选择custom并运行console.log(newSelection, PossibleSelections.CUSTOM, typeof newSelection, typeof PossibleSelections.CUSTOM),我将得到custom custom string string

由于不清楚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;
}
}
};

打印稿操场

相关内容

  • 没有找到相关文章

最新更新