我的问题是如何使用像AmpersandJS这样的库或解析信任的其他库来使用类型记录构建(类)对象(我不确定这种模式是否有名称)。例如,Ampersand.JS使用一个函数(.extend)根据您的配置构建一个原型:
// This object contains the configuration that Ampersand uses to build my model.
var config = {
props: {
firstName: 'string',
lastName: 'string'
}
};
// Create a Person model with getters, setters, validation etc.
var Person = AmpersandModel.extend(config);
// A basic usage to create an instance of a Person object
var myPerson = new Person({firstName:"John", lastName:"Doe"});
myPerson.firstName = "NewJohn"; // runs the first name setter build by ampersand我很难用类型记录来实现上面的例子。对于其他库,如主干,您可以使用普通/直截了当的类型记录方法:
MyModel extends Backbone.Model{}但是,对于Ampersand.JS这样的库,我不能使用:
Person extends AmpersandModel{}因为这将永远不会执行AmpersandModel的定制extend()代码,该代码基于传递给extend()函数的配置构建原型。
我不知道其他库也面临同样的问题,他们使用什么解决方案。任何使用Ampersand模式的库的例子都可能有帮助。
发布于 2014-08-11 14:37:29
下面是我想出的--首先我删除了Ampersand.js模块的定义。我从来没有使用过Ampersand,所以就离开他们的文档:
declare module ampersand {
interface AmpersandState {
// todo...
}
interface AmpersandCollection {
// todo...
}
interface ModelExtendOptions {
parse?: boolean;
parent?: AmpersandState;
collection?: AmpersandCollection;
}
interface ModelSaveOptions {
patch?: boolean;
}
interface AmpersandModel<TProps> {
save: (attrs?: TProps, options?: ModelSaveOptions) => void;
// todo: fetch, destroy, sync, etc...
}
interface AmpersandModelConstructor<TProps, TModel extends AmpersandModel<any>> {
new (attrs: TProps, options?: ModelExtendOptions): TModel;
}
interface ExtendOptions {
props?: {};
session?: {};
derived?: {};
}
interface AmpersandModelStatic {
extend: <TProps, TModel extends AmpersandModel<any>>(options: ExtendOptions) => AmpersandModelConstructor<TProps, TModel>;
}
}
declare var AmpersandModel: ampersand.AmpersandModelStatic;下面是如何使用上述符号和模块定义来定义您自己的接口,等等。
由于类型记录、泛型和继承的局限性,您需要为每个模型类型创建两个接口:一个用于其属性,另一个用于组合属性和符号和基本模型:
// interface for person properties...
interface PersonProps {
firstName: string;
lastName: string;
}
// interface to tie everything together...
interface PersonModel extends PersonProps, ampersand.AmpersandModel<PersonProps> {
}
// use AmpersandModel's extend method...
var Person = AmpersandModel.extend<PersonProps, PersonModel>({ props: { firstName: 'string', lastName: 'string' } });
// at this point you now have full intellisense/type checking for the constructor and properties.
var me = new Person({ firstName: 'Jeremy', lastName: 'Danyow' });
me.firstName = 'Ron'; // yes!
me.eyeColor = 'Brown'; // compile error
https://stackoverflow.com/questions/25227309
复制相似问题