Hacker News new | ask | show | jobs
by ljm 661 days ago
In TS you can have two types, say:

    type A = { a: string; b: string }
    type B = { a: string; b: string; c: string }
If you created a new object like this:

    { a: “foo”, b: “bar”, c: “baz” }

It would satisfy both type A and type B.

That won’t work quite so easily in go without messing around a bit.

2 comments

I'm using something like this in one of my Go projects and I created explicit functions to allow programmers to use the larger type where the smaller one is required, which is normally disallowed by the language, by employing some cludgy unsafe package use and based on the assumption that the memory layout for the two types looks identical for the common "a" and "b" properties.

So far it hasn't bitten me in the behind, but I wouldn't advise anyone to use that logic for production code.

Go structs are nominally typed, so that is beyond the topic of structural/duck typing. Only the interface is structurally typed.

The difference between structural typing and duck typing is that one is evaluated at compile time, while the other at runtime. Typescript is erased before runtime, so it by itself does not exhibit duck typing features, although Javascript does.