打字稿:Helper class 嵌套方法 return

typescript: Helper class with nested method with return

我正在尝试通过在另一个方法之上调用方法来创建 JSON 帮助程序 class。即第二种方法从第一种方法获取结果并对其进行处理。此外,第一种方法应该给出 Class 对象。如果可能直接结果。

预期 api Helper 的结果如下。

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

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

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

我创建了一个 class 作为 JSON 方法并定义了这些方法。但不确定如何进步。找到下面的代码。

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 方法不应该在 JSONMethods 中不可用的 parse 方法之上。我可以把它设为私有。但是如何从解析中访问提取方法。

有点困惑。谁能支持一下。

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

而不是 entity: 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);