Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Split: Fix instantiations with unions and add strictLiteralChecks option #1067

Merged
merged 2 commits into from
Mar 2, 2025

Conversation

som-sm
Copy link
Collaborator

@som-sm som-sm commented Mar 2, 2025

This PR introduces a new strictLiteralChecks option for the Split type based on the discussions made in #1047.

This option currently defaults to false for backward compatibility but in the next major release it'd be better to update the default to true.

Why is defaulting to true better?
When non-literal strings are involved, the result produced by Split will most-likely be inaccurate. Consider this example:

import {Split} from "type-fest";

declare function split<
	S extends string,
	Delimiter extends string,
>(string: S, separator: Delimiter): Split<S, Delimiter, {strictLiteralChecks: false}>;

const result = split('a.b.c.d' as `a.b.${string}`, '.');
//    ^? const result: ["a", "b", string]

So, when strictLiteralChecks is disabled, splitting a.b.${string} by '.' returns ['a', string, 'z'], which is not accurate because the a.b.${string} type might hold a value like a.b.c.d, which, when split by ,, would result in ['a', 'b', 'c', 'd'], which wouldn't conform to the output type of ['a', 'b', string].

So, by default, it's better to prioritise accuracy over precision and simply return string[] in cases involving non-string literals.


This PR also fixes cases where Delimiter is a union:

type Current = Split<"a,b,c", "," | "b">;
//   ^? type Current = ["a" | "a,", "" | "b", "", "c"] | ["a" | "a,", "" | "b", "c"] | ["a" | "a,", "", "c"]

type Updated = Split<"a,b,c", "," | "b">;
//   ^? type Updated = ["a", "b", "c"] | ["a,", ",c"]

Closes #1047

@som-sm som-sm force-pushed the fix/add-strict-literal-checks-option-for-split branch from 52bb4fd to 9448128 Compare March 2, 2025 13:07
@sindresorhus sindresorhus merged commit cc93f85 into main Mar 2, 2025
13 checks passed
@sindresorhus sindresorhus deleted the fix/add-strict-literal-checks-option-for-split branch March 2, 2025 14:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants