2 回答

TA貢獻1770條經(jīng)驗 獲得超3個贊
我對肯定和可組合性也不是很熟悉,但是我認為interfaces可以幫助解決問題。您可以輕松擴展aninterface并將一個變量聲明為one。請查看以下示例,以了解如何使用和擴展接口。請注意,在這種特殊情況下,無需遍歷所有類。
type Monad = any;
interface Unit {
of(value: any): Monad;
}
const unit: Unit = {
of(value: any): Monad {
return value;
}
}
const notUnit: Unit = {};
const alsoNotUnit: Unit = {
isMaybe(value: any): boolean {
return false;
}
}
interface Maybe extends Unit {
isMaybe(value: any): boolean;
}
const maybe: Maybe = {
isMaybe(value: any): boolean {
return true;
},
of(value: any): Monad {
return value;
}
}
const notMaybe: Maybe = {
isMaybe(value: any): boolean {
return true;
}
};
const alsoNotMaybe: Maybe = {
of(value: any): Monad {
return value;
}
}
提醒您一點,因為我看到您使用了&交集類型運算符-交集類型當(dāng)前在Flow中是斷開的并且不一致。我建議暫時不使用它們。它們的大多數(shù)行為都可以通過其他更正確的方法來完成,例如散布算子或extends。

TA貢獻1852條經(jīng)驗 獲得超1個贊
我對您的意思不是很熟悉,“有什么方法可以使Flow產(chǎn)生積極的和可組合的合同嗎?” (我假設(shè)這是來自另一種語言嗎?),并且我還沒有按照您描述的方式使用流程;這是將函數(shù)定義定義為類型的一部分,但我希望這里的方法會對您有所幫助。
我在這里要做的第一件事是為 MaybeUnit
export type MaybeUnit = Unit &{
isMaybe: (obj): boolean
};
但是,我再一次不熟悉該函數(shù)是否屬于該類型。每當(dāng)我想要一個函數(shù)時,我都會定義一個類(可能帶有interface)而不是類型。這可能會將您的實現(xiàn)更改為如下所示:
interface IUnit {
of(value: any): Monad;
}
class Unit implements IUnit {
of(value): Monad {
return new Monad();
}
}
interface IMaybeUnit extends IUnit {
isMaybe({}): boolean;
}
class MaybeUnit extends Unit implements IMaybeUnit {
isMaybe({}): boolean {
return true;
}
}
希望這種方法可以解決您的問題。
更新:添加一個示例,說明我有時對管理器類所做的事情。這是一種非常冗長的方法,并且僅在某些情況下適用。當(dāng)使用流運行時以便在執(zhí)行時而不是在構(gòu)建時測試類型時,它也更加有用。
class UnitManager {
static UnitTypes:Map<string, IUnit>;
static RegisterUnitType( key:string, klass:Class ) {
UnitManager.UnitTypes.set( key, klass );
}
static CreateUnit( unit:IUnit ):Unit {
// test data to determine type
let type:string = UnitManager.GetUnitType( unit );
let klass:Class = UnitManager.UnitTypes.get( type );
return new klass( unit );
}
static GetUnitType( unit:IUnit ):IUnit {
// Magic. Your logic to determine the type based on the data provided. if you use flow-runtime, you can use instanceOf, otherwise I think you need to test if the keys exist in the data, or something.
}
}
一開始我沒有包括它,因為它不是很干凈,并且通常會是反模式。在某些情況下這很有用,我發(fā)現(xiàn)自己主要是為了避免循環(huán)依賴。
有時我會這樣做,以便每個類的構(gòu)造函數(shù)根據(jù)其類中的靜態(tài)“名稱”常量向管理器注冊自己。
添加回答
舉報