The Art of Type Arguments 9 exercises
Problem

Inferring Literal Types from any Basic Type

Here we have a function called inferItemLiteral which takes in a type parameter of t and returns that t on an object:


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

Now, because it's returning an object, we know from the previous explainers t

Loading exercise

Transcript

0:00 In this exercise, we have a function called inferItemLiteral. This item literal basically takes in a type parameter of T and returns that T on an object. Now, because it's returning an object, we know that, from the previous explainers, that we're going to have some issues with inference here.

0:18 It's not going to be inferring the A that we pass in, and it's not going to be inferring the 1, 2, 3 we pass in. It's instead going to be just inferring them as they're vague basic types, so string here and number here.

0:31 Now what we want to do is we want to make sure that results here, instead of being output string, is inferred as output A, and here, is inferred as output 1, 2, 3 instead. We also want to restrict anything else from being passed in. We only want to allow strings and numbers here.

0:47 With that information and knowing what we know from the previous explainers, see if you can solve this exercise. Good luck.