Interface or Type Alias in Typescript—A Short Opinionated Answer

Use type aliases for immutability and consistency, but interfaces may be preferred when it comes to error messages.

To reuse a type annotation for an object in Typescript (TS), you can use an interface or a type alias. Related to a discussion at my current job, at Ishavskraft, that–world wide–probably has occurred as many times as the universe is old:

Should we use interfaces or type aliases for reusing type annotations in TS?

Immutable type alias. No, I’m not refering to the readonly modifier which both interfaces and type aliases can use. Besides the different syntax, a “type cannot be changed after being created”. So when immutability of the type annotation itself makes sense, that’s your answer. But another question to consider is if immutability even makes sense for type annotation. It at least doesn’t make sense if object properties should be mutable (i.e., not compatible with Object.seal()).

Consistent type alias. “Interfaces may only be used to declare the shapes of objects, not rename primitives”. To annotate a primitive or any union type, only a type alias can be used. So a code base can consistently use only the type alias syntax.

Error message interface:

  • “Prior to TypeScript version 4.2, type alias names may appear in error messages, sometimes in place of the equivalent anonymous type (which may or may not be desirable). Interfaces will always be named in error messages”.
  • “Interface names will always appear in their original form in error messages, but only when they are used by name.”

For the most part, you can choose based on personal preference, and TypeScript will tell you if it needs something to be the other kind of declaration. If you would like a heuristic, use interface until you need to use features from type.

…so an opinionated answer.

Sveltekit structure

In a “types” folder in the “lib” folder, have one file per type/interface export, named accordingly.

Reference