我有一个服务,我想用它来从
JSON返回指定类型构建的对象.
我有一个MyClass类,它实现了一个定义FromJSON静态方法的静态类.
export interface InterfaceMyClass {
static FromJSON(json: any): any;
}
export class MyClass implements InterfaceMyClass {
constructor(){}
FromJSON(json: any): MyClass {
let instance = MyClass.create(MyClass.prototype);
Object.assign(instance, json);
// Some other code specific to MyClass
return instance;
}
}
我不知道如何调用我在服务中传递参数的泛型类的静态方法.
我的服务如下:
export class MyService<T extends InterfaceMyClass> {
getObject() {
let json = getExternalJson(...);
return T.FromJSON(json); // <-- How to call static method FromJSON from T class ?
}
}
我想用这种方式使用服务:
let service = new MyService<MyClass>();
let myObject = service.getObject(); // <-- Should by an MyClass instance (created by MyClass.FromJSON)
题:
如何调用此T.FromJSON方法?
奖金问题:实现静态方法的好方法是什么?我不认为我的MyClass的FromJSON方法是静态的.如果我在FromJSON之前添加静态单词,它会告诉我:
[ts] Class 'MyClass' incorrectly implements interface 'InterfaceMyClass'.
Property 'FromJSON' is missing in type 'MyClass'.
最佳答案 一些东西:
(1)接口不能有静态声明,例如:
interface MyInterface {
static myMethod(); // Error: 'static' modifier cannot appear on a type member
}
在打字稿中解决这个问题的方法是定义一个构建器/构造函数接口:
interface MyInterface {}
interface MyInterfaceBuilder {
new (): MyInterface;
myMethod();
}
(2)通用约束仅在编译时可用,但编译器会删除它们,因为javascript不支持它,例如:
class MyClass<T extends string> {
private member: T;
constructor() {
this.member = new T(); // Error: Cannot find name 'T'
}
}
编译成:
var MyClass = (function () {
function MyClass() {
this.member = new T(); // Error: Cannot find name 'T'
}
return MyClass;
}());
当查看js输出时,很清楚为什么编译器会抛出无法找到名称’T’错误,因为T无处可寻.
为了解决所有问题,这里有一个解决方案:
interface IMyClass {}
interface IMyClassBuilder<T extends IMyClass> {
new (): T;
FromJSON(json: any): any;
}
class MyClass implements IMyClass {
static FromJSON(json: any) {
return "";
}
}
class MyService<T extends IMyClass> {
private classToCreate: IMyClassBuilder<T>;
constructor(classToCreate: IMyClassBuilder<T>) {
this.classToCreate = classToCreate;
}
getObject(): T {
let json = getExternalJson(...);
return this.classToCreate.FromJSON(json);
}
}
let service = new MyService(MyClass);
let myObject = service.getObject();