DEV Community

Discussion on: My reflections on Golang

Collapse
 
gypsydave5 profile image
David Wickes

No, it is not the same. In Typescript, interfaces are implemented by intent as below unlike the implicit(which is what I don't like about it) way in Go

I must object. Although you can use interfaces to enforce contracts, they can also be used as structural sub-typing on fields - see this from the Typescript docs:

interface LabeledValue {
    label: string;
}

function printLabel(labeledObj: LabeledValue) {
    console.log(labeledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);

Notice we didn’t have to explicitly say that the object we pass to printLabel implements this interface like we might have to in other languages. Here, it’s only the shape that matters. If the object we pass to the function meets the requirements listed, then it’s allowed.

Thread Thread
 
deepu105 profile image
Deepu K Sasidharan

Oh Yes, you are right, I never thought of Duck typing coz I used to avoid it to the best of my abilities. Interestingly, it is considered as an issue by many and there is an open ticket in TS project to change this behavior as it can cause unexpected bugs.

My problems with Go is in enforcing contracts and not in typing but regardless I understand what you mean and to be fair the exact same implicit behavior can be achieved in Typescript as well which I hated.

class Vehicle {
    run(): void { console.log('Vehicle.run'); }
}

class Task {
    run(): void { console.log('Task.run'); }
}

function runTask(t: {  run(): void }) {
    t.run();
}

runTask(new Task());
runTask(new Vehicle());

But a difference, however, is that in TS its is not the only way and I have the choice to do things explicitly without relying on the implicit behavior. And I have always used the explicit way in TS projects as far as I could remember. And seems like there are ways to workaround but they are quite verbose

Anyways, unlike Go, TS is just a superset of JS which is completely dynamic(so in the end, all the types and interfaces, etc are only syntax sugars) and due to the weak typed nature of JS allowing structural typing is the only way to emulate how JS works so its more of a limitation than a feature IMO.