Description
⚙ Compilation target
ES2020
⚙ Library
lib.es5.d.ts
Missing / Incorrect Definition
It is not wrong definition, but if it is possible, I would like to suggest add overloads for String.prototype.split
method
I like to use string template types instead of just string
as much as possible, and it works like a charm. The problem is that when I try to split my well-known string, it returns just string[]
type which isn't very descriptive
My suggestion is to add simple overloads:
- When the
separator
isstring
andlimit
is not provided orundefined
- When the
separator
isstring | RegExp
andlimit
is0
I added zero to the list because it is straightforward to implement that case, but if it means that I also should provide type checking for negative values, noninteger values and correct tuple splitting type then forget about it 😁
We can completely remove limit
from overloads. I added it just to get the same type for provided limit
as undefined
and not provided limit
otherwise the return type will be string[]
if the value of limit
is undefined
Sample Code
type Split<Source extends string, Separator extends string> = Source extends `${infer Left}${Separator}${infer Right}`
? [...(string extends Left ? string[] : [`${Left}`]), ...Split<Right, Separator>]
: Source extends ""
? Separator extends ""
? []
: [""]
: string extends Source
? string[]
: [Source];
interface String {
split<Source extends string, Separator extends string>(
this: Source,
separator: Separator,
limit?: undefined,
): Split<Source, Separator>;
split(separator: string | RegExp, limit: 0): [];
}
You can see types in action on playground (with examples)
Documentation Link
No response