如何改进此函数映射的typescript?
我正在学习有关typescript的更多信息,最近编写了以下代码:如何改进此函数映射的typescript?,typescript,Typescript,我正在学习有关typescript的更多信息,最近编写了以下代码: type Operator = '+' | '-' | '*' | '/' | undefined; const actions: { [operator: string]: Function } = { '+': (a: number, b: number) => a + b, '-': (a: number, b: number) => a - b, '*': (a: number, b
type Operator = '+' | '-' | '*' | '/' | undefined;
const actions: { [operator: string]: Function } = {
'+': (a: number, b: number) => a + b,
'-': (a: number, b: number) => a - b,
'*': (a: number, b: number) => a * b,
'/': (a: number, b: number) => a % b === 0
? a / b
: null,
undefined: (a: number) => a,
};
我觉得目前它的类型相当糟糕,通过某种方式提取出一个函数的概念,将一个或两个数字转换成一个单独的类型,它可能会更整洁
您对如何改进代码有什么建议吗?您可以定义一种函数类型:
type Operation = (a: number, b: number) => number;
然后:
这对我来说是个好问题
const actions: { [operator: string]: Operation } = {
...
}