TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Why doesn't an implementation use the types on its parameters from its interface?

Open HomenSimpsor opened this issue 10 years ago • 3 comments

interface Bank {
    balance: number;
    withdraw(x: number): number;
}

class PowellCountyBank implements Bank {
    balance: number = 0;

    withdraw(x) {
        return (this.balance - x);
    }
}

var b = new PowellCountyBank();

console.log(b.withdraw({}));
                     // ^ Expect type error here.

(Playground)

The implementation shows the return type of withdraw but not type for the parameter:

image

HomenSimpsor avatar Feb 02 '16 21:02 HomenSimpsor

Duplicate of #3667. Fix available in #6118.

ahejlsberg avatar Feb 02 '16 22:02 ahejlsberg

Actually, #6118 doesn't affect methods, only property initializers. Reopening as suggestion.

ahejlsberg avatar Feb 02 '16 22:02 ahejlsberg

Commit 055ae8cd5ca9838ad03a37f2386802c7cebea1b3 from #6118 adds method contextual typing as well. Here's a cut-down sample from the test (it works for extending classes, too):

interface Ringer {
    ring: (times: number) => void;
}
class Alarm implements Ringer {
    str: string;
    ring(times) {
        this.str = times; // error
    }
}

sandersn avatar Feb 02 '16 22:02 sandersn