Last #TypeScriptTuesday, we left off with a version of #redux-toolkit's `createAction` method that could be used with a mix of inferred and explicit #TypeScript Generic Arguments.
But that method would still take every `type` - including objects. Let's see how to restrict that.
This can be solved by using the `extends` keyword, which allows us to restrict a Type Argument. So here, we state that out `T` argument always has to be a valid `string`.
You could always override that restriction by using `any`.
But `extends` can do more than that...
Not only can you use any interface in `extends`, you can also reference other generic parameters.
This can - among other things - be used to "pick" types from another generic type. Before conditional types, this was the common way to do things like this:
And then there's this one weird trick: in #TypeScript, a generic argument can reference _itself_ in it's extends clause.
For example, this allows to restrict generic arguments to very explicit mapped types with an association between keys and values.
And that's it for now with Generics.
Next week, we're going to take a deeper look at Interfaces. See you then!
For now, if you want to play around with the examples from this week, here's a TypeScript playground:
This #TypeScriptTuesday, we're going to take a look at #TypeScript's interfaces.
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:
🧵👇
An interface can also extend another interface.
Not only that, but also some (but not all) types.
While last #TypeScriptTuesday we looked at #TypeScript Generics Basics, today we continue where we left off, by taking a closer look at type argument inference, pitfalls and workarounds. We will take a look at a simplified version of #redux-toolkit's `createAction` function.
🧵👇
Here, we call this function three ways:
1. With explicit type arguments. Everything is fine. 2. With inferred type arguments. P cannot be inferred, because it does not relate to any method argument. 3. With one explicit type argument. But why is the second argument not inferred?
// ActionCreator
const incrementAction = createAction(type);
This is because #TypeScript cannot mix explicit and inferred type arguments.
There is a PR for that at github.com/microsoft/Type…, but there is still discussion on what syntax to use.
Let's just assume that this is impossible and try to work around it.