Search code examples
typescriptclassgenericsinference

Typescript: Generic class type inference


This following seems quite simple but I am not sure what is causing the error. I've been looking around for quite awhile but I can't seem to find an answer.

class MyClass<T > {
  property: T = 5 // Error Here: Type '5' is not assignable to type T
}

const tester = new MyClass<number>() // OK

const numberValue: number = tester.property // OK
const stringValue: string = tester.property // Error as expected

I thought T would be inferred as number from 'property'. I feel like used to work in the past but I am not sure.

Typescript playground with examples


Update

These definitions also have the same errors.

class MyClass<T extends number> {
  property: T = 5 // Error Here: Type '5' is not assignable to type T
}

class MyClass<T extends object> {
  property: T = {} // Error Here: Type '{}' is not assignable to type T
}

Solution

  • This should never have worked. Whatever you write in the definition of a generic class or method has to be valid for all possible values of T for which the class or method might be used. The assignment property: T = 5 is not valid if someone does new MyClass<string>() so that T is string. Inference only occurs when you use a generic class or method.