2017-08-11 21 views
1

我學習更多關於打字稿,最近寫了這個代碼:我該如何改進我的打字稿以獲得這張功能圖?

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, 
}; 

我覺得目前它的相當差的類型,並且可以通過某種方式提取出它們取一個或兩個數字的功能的想法更整潔一個單獨的類型?

對於如何改進我的代碼,您有什麼建議嗎?

+3

這將是https://codereview.stackexchange.com/一個很好的問題 – Kai

回答

3

您可以定義一個函數類型:

type Operation = (a: number, b: number) => number; 

然後:

const actions: { [operator: string]: Operation } = { 
    ... 
}