Created
September 9, 2016 14:42
-
-
Save Huruikagi/c8197d3862be5a9538a8a8eb0c927f86 to your computer and use it in GitHub Desktop.
TypeScriptでif関数が使いたかった
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* if関数の簡易な実装。 | |
* 三項演算子をラップしているだけだけど、結構便利。 | |
* | |
* @param condition 判定条件 | |
* @param returns 判定条件が`true`なら`$then`, `false`なら`$else`を返却する | |
* @returns {T | null} | |
*/ | |
export function $if<T>(condition: any, returns: {$then: T, $else?: T}): T | null { | |
return condition ? returns.$then : returns.$else; | |
} | |
// 使用例 | |
const result: string = | |
$if((1 > 2), { | |
$then: "A", | |
$else: $if((1 == 1), { | |
$then: "B", | |
$else: "C" | |
}) | |
}); | |
console.log(result); // B |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment