如果一個函式f: (X => Y) | undefined可能是未定義的,并且x: X已定義,那么我們可以使用可選鏈運算子來?.應用于:fx
f?.(x) // ok, no problem if `f` is undefined
但是當f: X => Y定義并且x: X | undefined可能未定義時,似乎沒有任何語法可以“映射” f“可選” x:
f(?.x) // not valid syntax; Unclear what to do when `x` is undefined
我可以嘗試實作交換andpipeTo的順序,然后讓它再次使用,如下所示:fx?.
function opt<X>(x: X | undefined): { pipeTo<Y>(f: (a: X) => Y): Y } | undefined {
return typeof x === 'undefined' ? undefined : {
pipeTo<Y>(f: (a: X) => Y): Y {
return f(x)
}
}
}
然后我可以使用 as opt(x)?.pipeTo(f),例如:
function square(n: number): number { return n * n }
for (const x of [42, undefined, 58]) {
console.log(opt(x)?.pipeTo(square))
}
是否有任何不那么繁瑣的標準解決方案可以將肯定存在的物件f應用于可能未定義的物件x?
澄清:“麻煩”:=任何迫使我寫下子運算式x兩次,或者用無意義的輔助變數使范圍混亂的東西。
uj5u.com熱心網友回復:
就像您正在查看Nullable<T>型別操作(定義為
type Nullable<T> = T | null | undefined
) 作為函子,并希望對其執行函子fmap動作,將表單的一個函式轉換f為表單的(x: X) => Y另一個函式(x?: Nullable<X>) => Nullable<Y>。我不認為有任何內置功能會以這種方式運行,我也不能權威地談論它在第三方庫中的存在,但你可以很容易地自己撰寫它:
const fmapNullable = <X, Y>(f: (x: X) => Y) =>
(x?: Nullable<X>): Nullable<Y> => x == undefined ? undefined : f(x);
然后使用它:
function square(n: number): number { return n * n };
for (const x of [42, undefined, 58]) {
console.log(fmapNullable(square)(x)?.toFixed(1))
// "1764.0";
// undefined;
// "3364.0"
}
從語法上講,我認為您無法獲得像可選鏈接運算子 ( ?.)那樣簡潔的符號;畢竟,TypeScript 不是 Haskell。你可以縮短“ fmapNullable”,但你仍然會應用一個函式,所以充其量你會有類似$_$(square)(x). 那好吧!
Playground 代碼鏈接
uj5u.com熱心網友回復:
這看起來像陣列,所以這里有一個陣列實作給你
function nonNullable<T>(v: T | null | undefined): v is T {return v != null}
class OneOrZeroArray<T> extends Array<T> {
pipe<V>(mapper: (v: T) => V) {
return this.map(mapper).filter(nonNullable)
}
pop(): T | undefined {
return super.pop();
}
static from<T>(item?: T | null | undefined): OneOrZeroArray<T> {
let a = new OneOrZeroArray<T>();
if (item != null) a.push(item);
return a;
}
}
function opt<T>(v: T | null | undefined) {return OneOrZeroArray.from(v)}
function square(n: number): number { return n * n }
for (const x of [42, undefined, 58]) {
console.log(
opt(x).pipe(square).pop()
)
}
uj5u.com熱心網友回復:
某人,某處,可能被認為是猴子補丁Function:
Function.prototype.$ = function (x) {
return typeof x === 'undefined' ? undefined : this.apply(null, [x])
}
似乎有效,恰好有兩個語法開銷字符:
function square(x) { return x * x }
square.$(42) // 1764
square.$(undefined) // undefined
請不要這樣做。即使我們可以,也不意味著我們應該這樣做。
(另外,它是 JS,因為我目前不想嘗試通過 TS 編譯器擠壓它)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/521756.html
