【问题标题】:Flowtype - how to write declaration for class factories, such as Backbone Models?Flowtype - 如何为类工厂编写声明,例如骨干模型?
【发布时间】:2016-01-06 13:14:54
【问题描述】:

大量的谷歌搜索和阅读 Flow 文档和示例并没有显示 Javascript 中非常常见的模式的任何示例 - 具有返回类的函数。一个典型的例子是 Backbone:

var User = Backbone.Model.extend({
  getFullName: function() {
    return this.get('firstName') + ' ' + this.get('lastName');
  }
});  


var exampleUser = new User();
exampleUser.set('firstName', 'Johny'); //set() is a method from Backbone.Model
exampleUser.set('lastName', 'Something');
exampleUser.getFullName(); //method coming from User class

在 JSDoc 中,我可以对类进行如下注释,一些 IDE 能够找出一个不错的自动完成功能:

/**
 * @class User
 * @augments Backbone.Model
 */
var User = Backbone.Model.extend(/**@lends User.prototype */{
  getFullName: function() {...}
});

有什么方法可以在 Flow 中正确标注这种模式?

【问题讨论】:

    标签: javascript backbone.js flowtype


    【解决方案1】:
    /* @flow */
    
    class Model {
        get(name: string): any {}
        set(name: string, value: any): void {}
    }
    
    function extend<T>(def: T): Class<Model & T> {
        throw new Error('not implemented')
    }
    
    var User = extend({
        getFullName: function() {
            return this.get('firstname') + this.get('lastname')
        }
    })
    
    var a = new User
    
    a.get('firstname')
    a.getFullName()
    // a.notExisting give error
    

    我使用intersection typegeneric type 来表示'给定一个定义对象类型T,返回一个ClassModelT'的模式

    此代码在 brew-shipped flow 0.11 下编译


    以下是我个人对流量的看法。我不得不同意流文档很少。了解其特性的最佳方法可能是阅读 flow 的 React annotation and flow's source. Flow 是基于复杂的类型推断算法,它允许您在没有注释的情况下对程序进行类型检查。因此 Flow 旨在让您无需注释,其文档也是如此。然而,类型推断并没有那么先进,可以让人们免于注释。你的代码就是一个例子。

    【讨论】:

    • 只是一个小问题:Flow 不使用 H-M 类型推断。它使用流分析(因此,流)。感谢您提供这个答案!
    猜你喜欢
    • 1970-01-01
    • 2016-02-07
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 2019-09-06
    相关资源
    最近更新 更多