Skip to content

Instantly share code, notes, and snippets.

@Huruikagi
Created September 9, 2016 14:42
Show Gist options
  • Save Huruikagi/c8197d3862be5a9538a8a8eb0c927f86 to your computer and use it in GitHub Desktop.
Save Huruikagi/c8197d3862be5a9538a8a8eb0c927f86 to your computer and use it in GitHub Desktop.
TypeScriptでif関数が使いたかった
/**
* 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