Skip to content

Commit

Permalink
Split: Just return string[] when S or Delimiter is non-literal
Browse files Browse the repository at this point in the history
* Use `IsStringLiteral` for conditional branches, which is more appropriate than `string extends ..`
* Add test cases where `S` or `Delimiter` is not `string` itself but also not a literal (e.g., Uppercase<string>)

Co-authored-by: Som Shekhar Mukherjee <[email protected]>
  • Loading branch information
ghaaj and som-sm committed Jan 23, 2025
1 parent 617a52b commit 784facc
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 17 deletions.
12 changes: 5 additions & 7 deletions source/split.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type {ArrayValues} from './array-values';
import type {Substrings} from './internal';
import type {IsStringLiteral} from './is-literal';

/**
Represents an array of strings split using a given character or character set.
Expand All @@ -24,11 +24,9 @@ array = split(items, ',');
export type Split<
S extends string,
Delimiter extends string,
> = string extends S
? string[]
: string extends Delimiter
? [S] | SplitHelper<S, ArrayValues<Substrings<S>>>
: SplitHelper<S, Delimiter>;
> = IsStringLiteral<S | Delimiter> extends true
? SplitHelper<S, Delimiter>
: string[];

type SplitHelper<
S extends string,
Expand Down
14 changes: 4 additions & 10 deletions test-d/split.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,15 @@ expectType<

// Split non-literal string by literal string.
expectType<string[]>(split(null! as string, 'foobar'));
expectType<string[]>(split(null! as Uppercase<string>, 'foobar'));

// Split non-literal string by non-literal string.
expectType<string[]>(split(null! as string, null! as string));
expectType<string[]>(split(null! as `pre${string}`, null! as `${number}`));

// Split literal string by non-literal string.
expectType<
| ['ABCDEF']
| ['', '']
| ['', 'F'] | ['A', '']
| ['', 'EF'] | ['A', 'F'] | ['AB', '']
| ['', 'DEF'] | ['A', 'EF'] | ['AB', 'F'] | ['ABC', '']
| ['', 'CDEF'] | ['A', 'DEF'] | ['AB', 'EF'] | ['ABC', 'F'] | ['ABCD', '']
| ['', 'BCDEF'] | ['A', 'CDEF'] | ['AB', 'DEF'] | ['ABC', 'EF'] | ['ABCD', 'F'] | ['ABCDE', '']
| ['A', 'B', 'C', 'D', 'E', 'F']
>(split('ABCDEF', null! as string));
expectType<string[]>(split('ABCDEF', null! as string));
expectType<string[]>(split('ABCDEF', null! as Capitalize<string>));

// Recursion depth at which a non-tail recursive implementation starts to fail.
const fiftyZeroes = '00000000000000000000000000000000000000000000000000';
Expand Down

0 comments on commit 784facc

Please sign in to comment.