【问题标题】:How do I get strict type checking on flowtype interfaces to constructor arguments for classes?如何对流类型接口对类的构造函数参数进行严格的类型检查?
【发布时间】:2016-11-12 06:27:06
【问题描述】:

当使用接口作为构造函数的参数时,是否可以获得更严格的编译时间检查?默认行为似乎过于宽松。

例如给定以下类:

// @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

【问题讨论】:

    标签: javascript flowtype


    【解决方案1】:

    显然是a known issue

    现在函数实例属性的类型为any,即使它们未定义。 :(

    我的问题因重复而关闭。这解释了我的问题中的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-13
      • 2010-11-11
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多