简体   繁体   中英

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

I'm using Typescript 2 and trying to write a universal parser-method for database objects. I'm using TypedJSON and can't get the parameters in the correct way. My code:

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);
    }
}

The Method expects something like:

/**
* 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;

My code has the following error:

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

I tried numerous things but can't get it right. Maybe someone can help.

When you use the {new (): T;} type annotation that indicates a constructor.

To support this, you need to make a couple of changes in your parseToInstance function. First, rather than model: T (nice pun) you need to annotate the type as {new():T} to indicate it's definitely a constructor. Unlike some other popular languages TS generics won't always describe classes so this needs to be specified. Second, you shouldn't be calling new on model before you pass it in. That would kind of undo the point of passing a constructor function.

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 you dropped a closing paren on parse, I added it back.

It should probably be something like:

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

Two changes:

  1. It's { new(): T } instead of just T
  2. You shouldn't pass new model , just the model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM