如何使用接口类型执行动态类型测试
how to perform a dynamic type test with an interface type?
这是一个SSCCE。以下代码:
// @flow
'use strict';
declare interface ICat {
purr(): string;
}
class Animal {
askToBeStrokedAsACat() {
strokeAsACat(this); // Flow complains here
}
}
function strokeAsACat(a: ICat) {
a.purr();
}
class Cat extends Animal {
purr() {
return 'purr';
}
}
const cat = new Cat();
cat.askToBeStrokedAsACat();
。导致 Flow 在 strokeAsACat
的函数调用时抱怨。投诉是(为简洁起见进行了编辑):
property `purr` of ICat not found in class Animal
投诉是合理和可理解的。
根据动态类型测试所写的内容,我应该能够简单地执行以下操作:
class Animal {
askToBeStrokedAsACat() {
if (this instanceof ICat)
strokeAsACat(this);
}
}
。相反,上述内容失败并显示:
ICat. type referenced from value position
另外,由于接口被转译掉,ICat
在运行时不可用,因此在运行时上述内容会失败:
ReferenceError: ICat is not defined
因此,确定此时的this
句柄是类似ICat
对象的唯一方法是执行以下操作:
class Animal {
askToBeStrokedAsACat() {
if (this instanceof Cat)
strokeAsACat(this);
}
}
。但这是名义上的,而不是结构类型,并且违背了使用接口的目的 ICat
如果我再添加几个ICat-like
类,我将不得不将我的动态类型测试编写为:
(this instanceof Cat) || (this instanceof BobCat) || (this instanceof Lynx)
所以我的问题是:
- 有没有办法对
interface
进行结构动态型式试验? - 有没有其他方法可以有效地压制 Flow 对该特定线路的抱怨?
我Flow
版本是:
$ npm ls --depth 0 | grep flow-bin
├── flow-bin@0.27.0
有没有办法对接口进行结构动态类型测试
不,这是不可能的。您可以测试对象具有属性和函数,但是在运行时如何知道它是签名?
不过,您应该很少需要它。例如,在代码中,您可以将askToBeStrokedAsACat
留空Animal
并在Cat
子类中覆盖它。
相关文章:
- 如何在谷歌电子表格脚本中测试范围参数的类型
- 正在测试Form Helper创建的输入类型
- 类型错误:无法读取未定义的属性“apply”,在测试中使用 javascript apply
- AngularJS Jasmine测试:类型错误:'未定义'不是对象
- Ionic V2和Cordova插件-未捕获类型错误:无法设置属性'测试'为null
- 没有返回类型的函数的Javascript单元测试
- 窗口对象通过对象类型测试,但 hasOwnProperty 导致错误
- 使用超级测试测试 koa 路由时,内容类型标头始终相同
- 为什么我的余烬测试给我类型错误:“未定义”不是一个函数
- 什么是上下文中静态类型javascript的示例,以更好地进行单元测试
- 循环这个.props.children我如何测试他们的类型
- 类型错误:parsed 在 angularjs 服务单元测试中未定义
- 角度业力测试在 $scope.$parent 函数上获得“类型错误:'未定义'不是一个函数”
- 带有外部依赖项的Jasmine单元测试指令失败,类型错误:'[object对象]'
- Firefox 23中的QUnit测试:;类型错误:document.setUserData不是函数;
- Mocha API测试:获取'类型错误:app.address不是函数'
- 测试函数参数的数据类型的正确性
- angularjs因果报应测试类型错误$route
- gullow因果报应测试类型错误:服务器不是一个函数
- 如何使用接口类型执行动态类型测试