TypeScript is misleading you about String.split
TypeScript will tell you that String.prototype.split returns a string[].
When destructuring the returned value, it will indicate that
all values are strings:
const [a, b] = "test".split("/");
// a: string
// b: string
When executing the code, a is a string but b is... undefined.
Run this example
and look at the logs. If you were depending on b to be a string at runtime,
you will run into a TypeError.
[LOG]: "string"
[LOG]: "undefined"
This was surprise number one[1].
The second was
MDN seeming to confirm
that String.prototype.split returns a string[]. It does mention undefined
as possible return value when using a regex separator.
Huh. Most of the "JS is weird" discourse online is overblown, but this one is truly strange. Am I missing something?
Shoutout to Kamran for the quality code review ↩︎