This specific function is designed to take a constructor that requires a string
argument and then outputs an instance of the constructed value T
:
function create<T>(constructor: new(value: string) => T): T {
return new constructor("Hello");
}
Let's now create a couple of test classes; one with a default constructor, and another with a constructor that takes a string
argument:
class Dog {
}
class Cat {
constructor(value: string) {
console.log(value);
}
}
The expected outcome is as follows:
const result: Cat = create(Cat);
"Hello"
However, using Dog
leads to some issues...
Issue 1
result
can be assigned as Dog
, but create
is invoked with Cat
:
const result: Dog = create(Cat);
"Hello"
Issue 2
result
can be defined as Cat
, but create
is used with Dog
. This is worrisome because not only is the declaration mismatched with the return type of create
, but also because Dog
lacks a constructor that accepts a string
argument:
const result: Cat = create(Dog);
Why does TypeScript allow this, and is there a method to enforce the correct behavior?
Try it out in the TypeScript Playground