Although it may seem simple, I am struggling to pinpoint the cause of this error. I have been searching for a solution for quite some time, but I have yet to find one.
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
Initially, I assumed that T would be inferred as a number based on the 'property' value. I vaguely remember this working in the past, but I am not entirely certain.
Check out the Typescript playground for more examples
Update
Even after implementing these definitions, I am still encountering 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
}