Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I don’t agree it’s a structural VS nominal difference. Typescript is structural, but it does have the “implements” keyword.

Which makes a million times more sense to me, because realistically when do you ever have a structure that usefully implements an interface without being aware of it?? The common use-case is to implement an existing interface (in which case might as well enforce adherence to the interface at declaration point), not to plug an implementation into an unrelated functionality that happens to expect the right interface.



TypeScript doesn't require a class to use it, though, because it's structurally typed. All that "implements Foo" in this example does is make sure that you get a type error on the definition of "One" if it doesn't have the members of "Foo".

If "Two" didn't have a "name: string" member, then the error would be on the call to "test".

    interface Foo {
        name: string
    }

    class One implements Foo {
        constructor(public name: string) {}
    }

    class Two {
        constructor(public name: string) {}
    }

    function test(thing: Foo): void {
        //...
    }

    test(new One('joe'));
    test(new Two('jane'));




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: