Flowtype-如何为类工厂(如骨干模型)编写声明? [英] Flowtype - how to write declaration for class factories, such as Backbone Models?

查看:70
本文介绍了Flowtype-如何为类工厂(如骨干模型)编写声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Extensive googling and reading through Flow docs and examples didn't show any example of a very common pattern in Javascript - having functions that return classes. A canonical example is 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可以弄清楚一个不错的自动完成功能:

In JSDoc, I could annotate the class as follows, with some IDEs being able to figure out a decent autocompletion:

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

有什么方法可以在Flow中正确注释此模式吗?

Is there any way how to properly annotate this pattern in Flow?

推荐答案

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

我使用交叉点类型给出定义对象类型T,返回一个Class都是ModelT '

I use intersection type and generic type to express the pattern that 'Given a definition object type T, return a Class that is both Model and T'

此代码在酿造流0.11下编译

This code compiles under brew-shipped flow 0.11

下面是我关于流程的个人想法.我必须同意流程文档稀缺.了解其功能的最好方法可能是阅读流程的反应注释和流的来源.流基于复杂的类型推断算法,该算法可让您对程序进行类型检查而无需注释.因此,Flow旨在使您无需注释,其文档也是如此.但是,类型推断并不是很先进,无法使人们免于注释.您的代码就是一个例子.

Below is my personal idea on flow. I have to agree that flow docs is scarce. The best way to learn its feature is probably reading flow's React annotation and flow's source. Flow is based on a sophisticated type inference algorithm, which allows you type-check a program without annotation. So Flow is designed to make you not annotate, and so does its documentation. However, type inference is not so advanced to free one from annotating. You code is an example.

这篇关于Flowtype-如何为类工厂(如骨干模型)编写声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆