Sunrabbit

Receiving Immutable Values with Generics

Created: 2024-10-30

Created: 2024-10-30 17:41

Sometimes, we want to use the same type as "hello" in generics, not just string.

However, this is one of the areas where type inference doesn't work well.

```


When developing libraries, we strive to make type inference as strong as possible for a better user experience.

```

We want the type to be inferred as shown above.


We can achieve this in several ways.

```

Using 'as const' and 'readonly' is one method,

but this requires the user to do it, not something the library developer can handle.


Therefore, TS 5.0 introduced a new keyword to allow library developers to handle this.


Using this keyword simplifies the process as follows:

```


This can be used with arrays and literal types, but unfortunately, it doesn't work with arrow functions.

Nevertheless, this is still good news for library developers and users alike.

Comments0