Typescript 中實現 Maybe
阿新 • • 發佈:2018-12-10
Maybe
在haskell裡,我們有:
Maybe a = Just a | Nothing
Typescript中實現
class Optional<T> {
private _isValid: boolean = null;
private _value: T = null;
constructor (v: T = null) {
if (v) {
this._isValid = true;
this._value = v;
} else {
this ._isValid = false;
}
}
getValue () {
return this._value;
}
isValid () {
return this._isValid;
}
}
// 使用
// 保證返回的是一個Optional物件,而不是Null
// 可以走通整個後續流程
function getPlayerById(id: number): Optional<Player> {
let player = world.players[i];
return new Optional (player);
}