The Art of Type Arguments 9 exercises

Accepting Multiple Literal Types

Adding T extends string, will stop anything else from being passed in, while getting us inference on the strings that are passed in:

export const inferItemLiteral = <T extends string>(t: T) => {
return {
output: t,

Now result1 is going to be inferred as "a" inst

Loading solution


0:00 The solution here relies on the knowledge that you picked up from the explainers. We know that we can say T extend string. What that will do is it will stop anything else from being passed in, but we will get inference on the strings that we do get passed in. This is being inferred as A.

0:15 We can do the same for a number too, so inferItemLiteral this number, it now gets inferred as a number, but we now can't pass strings in. It seems like we've got the same problem but going two different directions. What if we did T extends string or number? Now, the A gets inferred, and the 1, 2, 3 gets inferred, and you can't pass anything else in. This passes all of our tests.

0:40 This is a neat little trick that you can pick up when you want to accept multiple things into an identity function, or into a generic slot and you want them to be inferred to their literals. It hopefully should fit with your mental model that you've picked up so far with how TypeScript infers these literals.