Reputation: 727
Why in this snippet TypeScript does not notice that MadeFromString
class does not have a second boolean argument in its constructor and so is not appropriate for StringConstructable
interface:
interface ComesFromString {
name: string;
}
class MadeFromString implements ComesFromString {
constructor(public name: string) {
// Returns an object of type ComesFromString / MadeFromString
}
}
interface StringConstructable {
new (n: string, w: boolean): ComesFromString;
}
function makeObj(n: StringConstructable) {
return new n('hello!', false);
}
const test1 = makeObj(MadeFromString);
Yet here, it does notice that MadeFromString
does not have a boolean variable called w
:
interface ComesFromString {
name: string;
}
class MadeFromString implements ComesFromString {
constructor(public name: string) {
// Returns an object of type ComesFromString / MadeFromString
}
}
interface StringConstructable {
new (n: string): ComesFromString;
w: boolean; // ERROR
}
function makeObj(n: StringConstructable) {
return new n('hello!', false);
}
const test1 = makeObj(MadeFromString); // ERROR
Upvotes: 0
Views: 38
Reputation: 85241
This is by design. When checking if functions are compatible, typescript enforces that all the right data is being passed in. It does not try to make sure that the function does something with that data.
Consider if I wrote the following constructor, but no lines of code used the second argument:
constructor(public name: string, neverUsed: boolean) {
// the variable neverUsed is not used anywhere in the constructor
}
Presumably you agree that that should match StringConstructable
. But the variable is doing nothing. It's common in javascript to leave off variables you don't care about; they'll still be passed in, you just won't access them. And typescript's type system supports this.
For more information see this page
Upvotes: 3