2 回答

TA贡献1770条经验 获得超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;
}
}
提醒您一点,因为我看到您使用了&交集类型运算符-交集类型当前在Flow中是断开的并且不一致。我建议暂时不使用它们。它们的大多数行为都可以通过其他更正确的方法来完成,例如散布算子或extends。

TA贡献1852条经验 获得超1个赞
我对您的意思不是很熟悉,“有什么方法可以使Flow产生积极的和可组合的合同吗?” (我假设这是来自另一种语言吗?),并且我还没有按照您描述的方式使用流程;这是将函数定义定义为类型的一部分,但我希望这里的方法会对您有所帮助。
我在这里要做的第一件事是为 MaybeUnit
export type MaybeUnit = Unit &{
isMaybe: (obj): boolean
};
但是,我再一次不熟悉该函数是否属于该类型。每当我想要一个函数时,我都会定义一个类(可能带有interface)而不是类型。这可能会将您的实现更改为如下所示:
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;
}
}
希望这种方法可以解决您的问题。
更新:添加一个示例,说明我有时对管理器类所做的事情。这是一种非常冗长的方法,并且仅在某些情况下适用。当使用流运行时以便在执行时而不是在构建时测试类型时,它也更加有用。
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.
}
}
一开始我没有包括它,因为它不是很干净,并且通常会是反模式。在某些情况下这很有用,我发现自己主要是为了避免循环依赖。
有时我会这样做,以便每个类的构造函数根据其类中的静态“名称”常量向管理器注册自己。
添加回答
举报