如何对 类 的构造函数参数的流类型接口进行严格类型检查?
How do I get strict type checking on flowtype interfaces to constructor arguments for classes?
在使用接口作为构造函数的参数时,是否可以进行更严格的编译时检查?默认行为似乎过于宽松。
例如给出以下 class:
// @flow
'use strict';
import type { Bar } from './bar';
export default class Foo {
_bar: Bar;
_name: string;
constructor (bar: Bar, name: string) {
this._bar = bar;
this._name = name;
}
}
并且在另外一个地方定义了如下接口:
// @flow
'use strict';
export interface Bar {
doSomething(someArg: string);
}
如果我用某种原始类型创建一个无效的 Foo 实例,我会得到一个错误:
// In any of these flowtype checking works and fails because
// it knows those things are not Bar.
new Foo('bar', 'someName');
new Foo(1, 'someName');
new Foo({}, 'someName');
但是如果我做这样的傻事:
new Foo(new Function(), 'someName');
flowtype 对此非常满意,这甚至违背了最初定义接口的目的。如果我可以传入任何类型的实例对象并且 flowtype 没有看到传入的内容与接口不匹配,它应该像 {}
.
一样抛出错误
是否需要更改某些配置或我做错了什么?
编辑:
我认为这可能是一个错误并已提交 issue。
显然是 a known issue。
因为现在函数实例属性是 any
类型,即使它们是未定义的。 :(
我的问题因重复而被关闭。这解释了我问题中的问题。
在使用接口作为构造函数的参数时,是否可以进行更严格的编译时检查?默认行为似乎过于宽松。
例如给出以下 class:
// @flow
'use strict';
import type { Bar } from './bar';
export default class Foo {
_bar: Bar;
_name: string;
constructor (bar: Bar, name: string) {
this._bar = bar;
this._name = name;
}
}
并且在另外一个地方定义了如下接口:
// @flow
'use strict';
export interface Bar {
doSomething(someArg: string);
}
如果我用某种原始类型创建一个无效的 Foo 实例,我会得到一个错误:
// In any of these flowtype checking works and fails because
// it knows those things are not Bar.
new Foo('bar', 'someName');
new Foo(1, 'someName');
new Foo({}, 'someName');
但是如果我做这样的傻事:
new Foo(new Function(), 'someName');
flowtype 对此非常满意,这甚至违背了最初定义接口的目的。如果我可以传入任何类型的实例对象并且 flowtype 没有看到传入的内容与接口不匹配,它应该像 {}
.
是否需要更改某些配置或我做错了什么?
编辑:
我认为这可能是一个错误并已提交 issue。
显然是 a known issue。
因为现在函数实例属性是 any
类型,即使它们是未定义的。 :(
我的问题因重复而被关闭。这解释了我问题中的问题。