Matt Pocock
Matt Pocock

@mattpocockuk

12 Tweets 30 reads Feb 09, 2023
A brief thread.
'as const' has more uses than you might think.
Let's say we have a custom React hook, handling a piece of state called 'firstName'.
We're returning a tuple of [firstName, setFirstName], which we're hoping to use just like a useState.
The trouble is - when we go to use the tuple, it has a super-long type. Why?
Well, it's because our function isn't returning a tuple - it's actually returning an array - where the members could either be a string, or a dispatcher.
We need to tell TypeScript that we're not returning an array (of any length), but a tuple (of fixed length).
We could do that with a very lengthy return type annotation.
But it would be great if we could _force_ TypeScript to understand the type we're returning.
By adding 'as const' to the returned array, we force TypeScript to narrow it to a tuple.
Now, useFirstName returns a tuple where the first member is a string, and the second member is a function.
And we can happily use our function in the wild.
Let's do one more. Let's say you have a function called createUser:
When you hover it, you'll see that 'role' is not being inferred as 'admin', but by its wider type - string.
By narrowing 'role' to as const, you can force it to narrow into the literal 'admin':
So - as well as being great for declaring configuration objects, as const can also be used in a pinch to narrow something down to its literal value in a function return.
Liked this? You'll love my TypeScript course, coming out in just a few weeks:
totaltypescript.com

Loading suggestions...