4 ms·
You can totally simulate duck typing with Typescript, since it (only) supports structural typing. If your method only expects an object with an asString() metho
by mercurial 10y ago
You can totally simulate duck typing with Typescript, since it (only) supports structural typing. If your method only expects an object with an asString() method, you can do something like:
function useAsString(foo: {asString: () => string}) {
...
}
Note that the type we give for foo here is an anonymous type (though this would also work with an explicitly named type).
And now you can do this:
interface SomeInterface {
name: string;
asString: () => string;
}
let bob: SomeInterface = { name: "Bob", asString: () => "Bob" };
useAsString(bob);
And this works, because the interface SomeInterface has an asString() method. No inheritance in sight.
- qwertyuiop924 10y agoHuh. Pretty cool. Are the interfaces Go-style (must you declare a class/object as that interface, or is it just detected)? Because if it's not, than it's not duck typing, is it?
- Too 10y agoInterfaces in typescript are implicit, or auto detected. You dont have to say that a class implements an interface, if it has the correct properties it automatically fulfills the interface. It's like type safe ducktyping and it's super awesome.
- qwertyuiop924 10y agoThat's just compile-time verified duck typing. Not bad.
- betenoire 10y agoStatic weak types
- qwertyuiop924 10y agoNo, because you're not doing implicit type conversion, which is what weak typing implies.
- Roboprog 10y agoSounds like it works just like Go-lang, then. Is there a way to cast something anonymous, just a value read in from JSON, to such an interface? This would allow you to specify an important subset of things that an object needs to do, verify it in one place, then pass around the interface handle to anything that needed the underlying object in that role. Presumably, if the incoming object lacked the desired attributes, the "cast" would blow up sooner, during the assignment, rather than later, when the interface alias was used.