typescript - Any reason to put implements interface to class? -
i'm new type script, browsing tutorial , trying coding in playground found strange.
for example code:
class foobar implements ifoobar { full: string; constructor (public foo, public bar) { this.full = foo + bar; } } interface ifoobar { foo: string; bar: string; } function test(ifoobar: ifoobar) { return ifoobar.foo + ifoobar.bar; } var obj = new foobar("hello", "world"); document.body.innerhtml = test(obj);
works if put
class foobar implements ifoobar
or just
class foobar
so what's point of using interface if contract not enforced?
update main concern on line:
document.body.innerhtml = test(obj);
this should throw error right since foobar doesn't use implements ifoobar, , test(ifoobar: ifoobar) specified in method argument should accept ifoobar. me feels typescript plainly think foobar implements ifoobar though isn't.
typescript uses duck typing, means if members match, types considered compatible. that's why code still valid after removing implements ifoobar
- foobar
can treated ifoobar
since has members declared ifoobar
.
and typescript enforce contract. if remove/rename either member foo
or bar
, compiler generate errors.
Comments
Post a Comment