I've been playing a bit with interfaces with construct signatures in TypeScript, and I became a bit confused when the following failed to type check:
class Foo {
constructor () {
}
}
interface Bar {
new(): Bar;
}
function Baz(C : Bar) {
return new C()
}
var o = Baz(Foo);
The type error is:
Supplied parameters do not match any signature of call target:
Construct signatures of types 'new() => Foo' and 'Bar' are
incompatible: Type 'Bar' requires a construct signature, but Type
'Foo' lacks one (C: Bar) => Bar
The type of Foo's constructor is () => Foo, and that is what I thought that Bar said. Am I missing something here?
Best Answer
Here is an updated version of your code with a subtle change.
We define the
Bar
interface with whatever functions and variables we expect to be present.Next, we extend the
Bar
interface with theNewableBar
interface. This just defined a constructor that returns aBar
.Because
Foo
implementsBar
and has a constructor andBaz
requires aNewableBar
, everything is checked.This is a little more verbose than
any
- but gives you the checking you want.