const unknown: Array<unknown> = ? as unknown
#learning #typescript
31st of May 2021
♦
Well, you get the gist. It’s about the unknown. What prompted me to look into this was an error my compiler served to me. I do not understand the error. I don’t understand the solution. And I don’t understand why it’s necessary.
Conversion of type '(form: FormGroup) => { mismatch: boolean; } | null' to type 'FormGroup' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
So the error was solved by doing (variableName as unknown) as FormGroup. But this was not my first encounter with the great unknown. It happened with another error when ESlint server me a suggestion to change : object to Record
♦
The Great unknown
In 2018, uknown was introduced with TS 3.0 as a new type that is a type-safe counterpart of any. This introduces two main rules that differentiate these two types.
Anything is assignable to it but then uknown is assignable only to itself or the good old any. Since we don’t know what is really inside either of these two types it makes sense for them to overlap, and why unknown cannot be assignable to any more specified types.
There are also no operations permitted on an unkown variable without first asserting or narrowing it to some other type. This is perhaps one of the most important differences between it and any. It demands and gives us more oversight over what is happening with our variables, while still allowing some freedom.
So what do we need to do to manipulate an uknown variable? Well, one option would be to tell TS to trust us that we know what we are doing and use type assertion. Since TS won’t do any additional checks to make sure a variable is actually what we say it is, it will allow using of the type’s operations on it.
For a safer, but more verbose, way, we should use narrowing with typeof, instanceof operator, or some custom type guard. Marius Schulz wrote a great article about unkown where he dives much deeper with concrete examples and a good explanation of narrowing.
So should we all start using unknown instead of any? Well, I don’t know. When I was starting to learn TS, a good friend of mine said to me, that TS is like a safety belt. That once you get used to it, it feels wrong to code without it. I don’t think I’m that comfortable with it just yet, but any started to get just a bit of a sour taste to me. Maybe that’s how it starts.
Throughout the writing of this article, a song was going through my head. I had this idea of somehow tying it all together to this song. The Great Unkown. Well, it turns out there were too many unknowns on my mind, as the song is of course called The Great Beyond. Well, we can’t have everything we want.
But we still have the masterpiece that is the 2007 album R.E.M. Live.
♦
Sources: