Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you use an interface over a type alias in flow?

Tags:

The interface and type declarations seems to do the same thing. When do you use one over the other?

type Fooable = {   foo(): string } 

vs

interface Fooable {  foo(): string } 
like image 297
m0meni Avatar asked Apr 28 '16 02:04

m0meni


People also ask

What is the difference between type alias and interface?

// One major difference between type aliases vs interfaces are that interfaces are open and type aliases are closed. This means you can extend an interface by declaring it a second time. // In the other case a type cannot be changed outside of its declaration.

What are type aliases?

Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different shorter name and use the new one instead. It's useful to shorten long generic types.

What is Interface flow?

User Interface Flows show graphically how a user will navigate a solution's user interface.

What are type aliases in javascript?

A type alias is basically a name for any type. Type aliases can be used to represent not only primitives but also object types, union types, tuples and intersections.


1 Answers

This is a great question. Ideally there would be no difference between an interface and an object type. As implemented, there are a handful of (often subtle) differences between them.

The biggest difference is that Flow considers methods declared on an interface to be "read-only." This allows subtypes to be covariant w.r.t. methods, which is a very common pattern with inheritance hierarchies.

In time, I would like to see Flow unify these concepts, but until then here's my rule of thumb for choosing between interfaces and object types:

  • Use object types to describe bags of mostly data that are passed around in your app, e.g., props/state for React components, Flux/Redux actions, JSON-like stuff.
  • Use interfaces to describe service-like interfaces. Usually these are mostly methods, e.g., Rx.Observable/Observer, Flux/Redux stores, abstract interfaces. If a class instance is likely to be an inhabitant of your type, you probably want an interface.

Hope this helps!

like image 92
Sam Goldman Avatar answered Sep 20 '22 02:09

Sam Goldman