Skip to content

Commit 83184d2

Browse files
authored
Fixes split to return non-null first element in most cases.
Fixes microsoft#49635 Behavior similar to microsoft#49682 microsoft#49635 was originally rejected because JavaScript has a stupid edge case where `''.split('')` and `''.split(new RegExp(''))` return an empty array so we cannot assert that the first element is *always* a string. However, given that the vast majority of use cases for `split` include a literal separator, we can create a set of overloads that results in the non-empty literal separator returning a more narrow type that has a string for the first element. ```ts ''.split('') // []; type= string[] ''.split(new RegExp('')) // []; type= string[] ''.split('a') // ['']; type= [string, ...string[]] ''.split(new RegExp('a')) // ['']; type= string[] ``` Unfortunately, I don't know of a way to differentiate a regular expression literal and a regular expression so that case still always returns an empty first element even though I don't even think it is possible to have an empty regular expression literal. I don't *believe* there are any other edge cases where split can return an empty array, but if there are please let me know and I can try to update, or we can close the PR and just leave a comment on microsoft#49635 for the next person.
1 parent 04d4580 commit 83184d2

File tree

1 file changed

+2
-0
lines changed

1 file changed

+2
-0
lines changed

src/lib/es5.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,8 @@ interface String {
470470
* @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.
471471
* @param limit A value used to limit the number of elements returned in the array.
472472
*/
473+
split(separator: '', limit?: number): string[];
474+
split(separator: string, limit?: number): [string, ...string[]];
473475
split(separator: string | RegExp, limit?: number): string[];
474476

475477
/**

0 commit comments

Comments
 (0)