网站搜索

javascript - typescript:带有返回值的嵌套方法的辅助类


我正在尝试通过在一个方法顶部调用另一个方法来创建一个 JSON 辅助类。也就是说,第二个方法获取第一个方法的结果并进行处理。同时第一个方法应该返回类对象。如果可能的话,直接返回结果。

从 Helper 预期的 API 和结果如下。

JSONMethods.parse("{name: 'hello'}") // { name: 'hello'}

JSONMethods.parse("{name: 'hello'}").format() // { name: 'hello'}

JSONMethods.parse("{name: 'hello'}").extract(Department); // { id: 0, name: 'hello'}

我创建了一个名为 JSONMethods 的类,并定义了那些方法。但不确定下一步该怎么做。请看下面的代码。

class Department {
    id: number = 0;
    constructor() { }
}

class JSONMethods {
    private static data;
    static parse<U>(json: string | U): JSONMethods {
        if (typeof json == 'string') {
            this.data = JSON.parse(json);
        }
        else {
            this.data = json;
        }
        return json; // not actually returing JSONMethods
    }

    static format() {
         return this.data;
    }

    static extract<T>(entity: T) {
         return Object.assign(new entity(), this.data); // getting compilation issue with new entity(). as *Cannot use 'new' with an expression whose type lacks a call or construct signature.*
    }
}

我预期的结果如上。同时,extract 方法不应该在 parse 方法顶部可用,也不在 JSONMethods 中。我可以把它设为私有方法。但是如何从 parse 方法访问 extract 方法呢。

有点困惑。有人能帮忙吗?

答案#1

你需要传入类的构造函数,而不是类的实例。所以,不是 entity: T,而应该是 entity: new() => T

class JSONMethods {
    private static data;
    static parse<U>(json: string | U): typeof JSONMethods {
        if (typeof json == 'string') {
            this.data = JSON.parse(json);
        }
        else {
            this.data = json;
        }
        return this;
    }

    static format() {
        return this.data;
    }

    static extract<T>(entity: new () => T) {
        return Object.assign(new entity(), this.data); // getting compilation issue with new entity(). as *Cannot use 'new' with an expression whose type lacks a call or construct signature.*
    }
}

JSONMethods.parse("{name: 'hello'}") // { name: 'hello'}

JSONMethods.parse("{name: 'hello'}").format() // { name: 'hello'}

JSONMethods.parse("{name: 'hello'}").extract(Department); 

我还建议在这种情况下避免使用静态字段,如果有人没有按照你期望的方式使用这些函数,你以后可能会遇到麻烦。

class JSONMethods {
    private data;
    static parse<U>(json: string | U): JSONMethods {
        var r = new JSONMethods()
        if (typeof json == 'string') {
            r.data = JSON.parse(json);
        }
        else {
            r.data = json;
        }
        return r;
    }

    format() {
        return this.data;
    }

    extract<T>(entity: new () => T) {
        return Object.assign(new entity(), this.data); // getting compilation issue with new entity(). as *Cannot use 'new' with an expression whose type lacks a call or construct signature.*
    }
}

let s = JSON.stringify({name: 'hello'});
JSONMethods.parse(s) // { name: 'hello'}
JSONMethods.parse(s).format() // { name: 'hello'}
JSONMethods.parse(s).extract(Department);