When working with Typescript and default compiler options, there are strict rules in place regarding null values and uninitialized class attributes in constructors. However, with generics, it is possible to define a generic type for a class and create a new instance of the class without specifying the type!
class Foo<T> {
bar(item: T): void {
console.log('typeof T: ', typeof item)
}
}
const foo1 = new Foo<string>() // Type 'T' specified
foo1.bar('hello')
foo1.bar(6) // error TS2345: Argument of type '6' is not assignable to parameter of type 'string'
const foo2 = new Foo() // Type 'T' not specified
foo2.bar('hello')
foo2.bar(6) // Works without error
Could new Foo()
be considered incorrect?
In this case, I am using default compiler options that do not allow adding an extra attribute a: T
which would never be initialized.