所以在 TS 中我們有通用的恒等函式:
const identity = <A>(a: A) => a;
當然,如果我們呼叫該函式,那么 TS 就能夠推斷出型別引數A:
declare const baz: string
const foo = identity("bar") // A = "bar", so typeof foo = "bar"
const bar = identity(baz) // A = string, so typeof bar = string
但是如果我嘗試類似的東西
import { foldMap } from "fp-ts/Array"
import { getMonoidAll, Predicate } from "fp-ts/Predicate"
declare const predicates: Predicate<string>[];
const concatPredicates = foldMap(getMonoidAll<string>())(identity);
然后 TS 告訴我“型別A不可分配給型別Predicate<string>,因為它推斷
typeof foldMap(getMonoidAll<string>()) = <A>(f: (a: A) => Predicate<string>) =>
(fa: A[]) => Predicate<string>
并且它不明白如果A = Predicate<string>那么標識函式有效并且上面的構造期望輸入 type Predicate<string>[]。
當然,identity我可以使用,而不是使用(a: Predicate<string>) => a,但這樣做感覺有點麻煩,我真的很想能夠利用identity函式的通用性。
有什么辦法嗎?有什么方法可以為函式參考提供型別提示?畢竟,看起來不自然的冗長是(a: Predicate<string>) => identity(a)可行的,因為在這種情況下 TS infers A = Predicate<string>。
uj5u.com熱心網友回復:
我不確定為什么 TypeScript 無法identity正確推斷型別,但您可以將其作為一種解決方法:
const concatPredicates = foldMap(getMonoidAll<string>())(
identity as (a: Predicate<string>) => Predicate<string>
);
或者(以及我更喜歡這種情況),您可以使用concatAll:
import { concatAll } from "fp-ts/Monoid";
const concatPredicates = concatAll(getMonoidAll<string>());
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/516370.html
標籤:打字稿仿制药FP-TS
下一篇:打字稿將嵌套陣列轉換為型別
