Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why are structs interfaces and not type aliases? #20

Closed
codeliger opened this issue Mar 10, 2023 · 2 comments
Closed

Why are structs interfaces and not type aliases? #20

codeliger opened this issue Mar 10, 2023 · 2 comments

Comments

@codeliger
Copy link

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases

In typescript you can define and export type aliases.
I am curious what your thoughts are on picking interfaces instead of type aliases for go structs.

I am trying to use the instanceof keyword but it doesn't work on interfaces, so during runtime theres no way to determine if the object returned from my function matches the interface type annotation.

@tim-we
Copy link

tim-we commented Mar 25, 2023

Type aliases also do not exist at runtime so what difference does that make? AFAIK the only difference between interfaces and type aliases is that interfaces can be extended (adding new properties).

@gzuidhof
Copy link
Owner

There are advantages and disadvantages to using type or interface, both could work here. I personally tend to use interface to describe a simple object for interop (~duck typing), whereas type is reserved for more complex expressions. So I prefer the simpler interface type if that does the job. That has worked for me so far, but of course other people may prefer different flavors. If you Google it you will find arguments for either, there is not one better choice.

As tim-we commented, both do not have any runtime leftovers, so instanceof will not work on either. I would recommend a library like zod for runtime type validation.

I am happy to accept a PR that allows one to output type expressions instead for Golang structs, but I'm not sure what its advantage will be, maybe there is something Tim or myself are missing?

I'll close this topic and re-open it if there is a good usecase for the ability to switch between type and interface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants