簡體   English   中英

打字稿:用戶使用正確的參數:TS2345:類型'T'的參數不能分配給類型'new()=> any'的參數。

[英]Typescript: User the correct parameters: TS2345: Argument of type 'T' is not assignable to parameter of type 'new () => any'.

我正在使用Typescript 2,並嘗試為數據庫對象編寫通用的解析器方法。 我正在使用TypedJSON ,並且無法以正確的方式獲取參數。 我的代碼:

private static parseToInstance<T>(dbObject: string, model: T): T {
    try {
        console.log("parseToInstance()")
        let a = TypedJSON.stringify(dbObject);
        return TypedJSON.parse(a, new model, "whatever"
    } catch (err) {
        throw new ParseException(err);
    }
}

該方法期望如下所示:

/**
* Converts a JavaScript Object Notation (JSON) string into an instance of the provided class.
* @param text A valid JSON string.
* @param type A class from which an instance is created using the provided JSON string.
* @param settings Per-use serializer settings. Unspecified keys are assigned from global config.
*/
parse<T>(text: string, type: {new (): T;}, settings?: SerializerSettings): T;

我的代碼有以下錯誤:

Error:(125, 30) TS2345:Argument of type 'T' is not assignable to parameter of type 'new () => {}'.

我嘗試了無數次嘗試,但無法正確完成。 也許有人可以幫忙。

當您使用{new (): T;}類型注釋時,它指示構造函數。

為此,您需要在parseToInstance函數中進行一些更改。 首先,您需要將類型注釋為{new():T} ,而不是model: T (漂亮的雙關語),以表明它肯定是構造函數。 與其他流行語言不同,TS泛型不會總是描述類,因此需要指定。 其次,在傳遞模型之前,您不應該在模型上調用new 。這將消除傳遞構造函數的意義。

private static parseToInstance<T>(dbObject: string, model: {new():T}): T {
    try {
        console.log("parseToInstance()")
        let a = TypedJSON.stringify(dbObject);
        return TypedJSON.parse(a, model, "whatever");
    } catch (err) {
        throw new ParseException(err);
    }
}

ps,您在解析時放了一個結束括號,我又加了回去。

可能應該是這樣的:

private static parseToInstance<T>(dbObject: string, model: { new(): T }): T {
    ...
    return TypedJSON.parse(a, model, "whatever");
}

兩項更改:

  1. 它是{ new(): T }而不是T
  2. 您不應該傳遞new model ,僅傳遞model

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM