Identity Functions 5 exercises
Problem

Identity Functions as an Alternative to the `as const`

In this section, we'll be looking at how we can use identity functions to power up inference in our apps.

An example of an identity function is the asConst function. It takes in a parameter T and the type argument T and returns t.


export const asConst = <T>(t: T) => t;

Loading exercise

Transcript

0:00 In this section, we're going to be exploring the power of identity functions. Here we have a function which is called asConst, and what it does is it takes in a T here, which is saved into this type argument of T, and just returns it. What you end up with is this fruits here is basically whatever's being passed in.

0:19 We have this asConst here, but it's not really acting like an asConst. We have name and price, but we're not getting the specific name and the specific price.

0:31 We can make it work by just passing it in as const and then actually all of these types pass here, but this is pretty ugly for people to pass in. Here what it does is it applies a readonly to the array, so you can't add members to that fruit array.

0:46 If we try, then if we go fruits.push, we can't even push to it because it's readonly, then it also makes all of the name and price stuff readonly as well, just like an asConst would. Wouldn't it be great if we could actually get this working without needing the user to specify asConst?

1:05 This happens all the time when you're building things where you need the user to pass in a specified config and you want that config to be manipulable by the types themselves.

1:14 This is actually a re-recording. I had an earlier version of this, where we used something called F.Narrow from ts-toolbelt, but since TypeScript 5., there's a new tool that we can use to make this work.

1:26 I think you've got all the clues you need. There'll be a couple of links below, too. Good luck.