在Flow中强制转换变量

时间:2018-10-31 18:20:32

标签: javascript flowtype

lib中的单独文件。无法直接访问这些类型。

fileA.js

export class MyTypeASuper {
  moof: string
};

lib中的单独文件。无法直接访问这些类型。

导入fileA.js

fileB.js

export class MyTypeBSuper {
  foo: MyTypeASuper
};

主lib文件导入了我的代码

这将导入fileA.js和fileB.js

index.js

export class MyTypeA extends MyTypeASuper {
  test() {}
};

export class MyTypeB extends MyTypeBSuper {
  test() {}
};

我使用lib的代码

我导入index.js,因此无法访问Super类。

const test: MyTypeB = new MyTypeB();

const a:MyTypeA = (test.foo: MyTypeA);

所有这些给我一个Cannot cast 'test.foo' to 'MyTypeA' because 'MyTypeASuper' is incompatible with 'MyTypeA'错误。

https://flow.org/try here

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您不能将超级类直接转换为子类。

这是您要尝试做的事情的简化。

class Base {}
class A extends Base {}
class B extends Base {}

// You CAN cast a child class to a super class
const a = new A()
const castBase: Base = a

// CANNOT cast a super class to a child class
const base = new Base()
const b: B = base // flow error that you are getting

// A runtime check must be performed to cast this,
// because the type system cannot guarantee type
// safety at compile time.
if (base instanceof B) {
  const bTested = base
} else {
  throw new Error('base is not an instance of B')
}

try flow

很显然,base既不是A也不是B的实例。但是,由于所有子类也是其父类,因此可以将子类转换为父类。

如果要将超类类型视为子类类型,则必须进行运行时检查,因为类型系统会说该实例可以是超类或任何其他基类。而且由于无法确切知道,您必须进行检查。