Typescript: TS doesn't work well with generics and classes as props

Created on 5 Sep 2017  路  2Comments  路  Source: microsoft/TypeScript



TypeScript Version: 2.3.4 , 252

Code

class Container<TT> {
    attr: TT
  }

class AttrX {
    hello: string = 'max'
}

const createClass = <T>(x: T): typeof Container => {
    return class ExtendedContainer extends Container<T> {}
}

const X = createClass(AttrX)
const x = new X()
console.log(x.attr.hello)

Expected behavior:
It's compiled

Actual behavior:
I see error

Type 'typeof ExtendedContainer' is not assignable to type 'typeof Container'.
  Type 'ExtendedContainer' is not assignable to type 'Container<TT>'.
    Types of property 'attr' are incompatible.
      Type 'T' is not assignable to type 'TT'.

Most helpful comment

Looks like you're dealing with the static side of the class in a couple places where you really want the instance side. This seems to work

const createClass = <T>(x: new() => T) => {
    return class ExtendedContainer extends Container<T> {}
}

All 2 comments

Looks like you're dealing with the static side of the class in a couple places where you really want the instance side. This seems to work

const createClass = <T>(x: new() => T) => {
    return class ExtendedContainer extends Container<T> {}
}

@jwbay awesome, thank you

Was this page helpful?
0 / 5 - 0 ratings