Interfaces are different from types and both have their strengths in different situations.
Let's take a look.
This is just some interface definition - again an example from the #redux types:
🧵👇
Not only that, but also some (but not all) types.
The rule of thumb here is: if the type is well-known and could be written as an interface, it can be extended. {
meta: number;
}" src="/images/1px.png" data-src="https://pbs.twimg.com/media/EPZFwGmWkAEwwKG.jpg">
If you index by string and number, the value indexed by number has to be a subset of the value indexed by string. // Error: Numeric index type 'number' is not assignable to string index type 'string'.ts(2413)
[key: number]: number;
}
" src="/images/1px.png" data-src="https://pbs.twimg.com/media/EPZFw8KWsAMbDJi.jpg">
Since TS3.7, types have become "lazier" and they allow for most recursion, too.
Just remember, if something doesn't work as a type, an interface might still work fine. leftOperand: number | ArithmeticsOperation;
rightOperand: number | ArithmeticsOperation;
}" src="/images/1px.png" data-src="https://pbs.twimg.com/media/EPZFxsmXsAEDkL7.jpg">
Types, as they are eager, often display all their definition in error messages, exposing implementation details.
Interfaces just show their name.
We used this in #redux-toolkit got get more legible autocompletion & errors.
/*
* before RTK 1.2.0, this was:
*
* WithTypeProperty
* "test", number, never, never>, "test"
* >
*
* it is now:
*
* ActionCreatorWithPayload
*/
const testAction = createAction
I hope you've learned something today, and I'll see you next #TypeScriptTuesday. 👋
You can find all examples in a TypeScript playground here: typescriptlang.org/play/#code/LAK…