1

Trying to override a method in a child class, with a generic return type, and coming up with this error. I've been reading could be instantiated with a different subtype of constraint 'object' but I can't wrap my ahead around to my scenario. Any advise?

Type '{ deployments: { [deploymentId: string]: string[]; }; }' is not assignable to type 'SomeInterface'.
  '{ deployments: { [deploymentId: string]: string[]; }; }' is assignable to the constraint of type 'SomeInterface', but 'SomeInterface' could be instantiated with a different subtype of constraint '{}'.(2322)
class SomeClass {
    testGenericMethod<T>(): T {
        throw new Error('Implement this.')
    }
}

interface SomeInterface {
  deployments: { [deploymentId: string]: Array<string> }
}

class ImplementSomeClass extends SomeClass {
    testGenericMethod<SomeInterface>(): SomeInterface {
        const deployments: { [deploymentId: string]: Array<string> } = {}
        return  { deployments }
    }
}

Playground Link

gruuuvy
  • 2,028
  • 4
  • 31
  • 52
  • The linked post had an answer that says this message is sometimes because of duplicate type declarations. Try `testGenericMethod(): SomeInterface {` – Ruan Mendes Feb 16 '20 at 01:35

1 Answers1

0

You are using a generic variable <SomeInterface> which overrides the interface definition in the scope of your function.

Use another generic variable. For instance, if it needs still to be a SomeInterface:

class ImplementSomeCLass {
    testGenericMethod<T extends SomeInterface>(): SomeInterface {
        const deployments: { [deploymentId: string]: Array<string> } = {}
        return  { deployments }
    }
}

Remember that in function definition, the generic types are variables. You can assign them default values

testGenericMethod<T = SomeInterface>(): SomeInterface {/** **/}

or you can constraint them to some types:

testGenericMethod<T extends SomeInterface>() : SomeInterface {/** **/}

In the former case, you can call your function with any type:

const myInterface = testGenericMethod<any>();

In the later case, you can use any type satisfying the constraint:

const myInterface = testGenericMethod<SomeInterface & MyOtherInterface>();
cghislai
  • 1,751
  • 15
  • 29
  • Thanks. I realized I mistyped the sample code. I really want `class ImplementSomeClass extends SomeClass` (extends SomeClass). I tried your suggestion of `` and it now says: `'SomeInterface' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.`. I've updated the TypeScript Playground. – gruuuvy Feb 16 '20 at 01:23