Skip to content
New issue

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

By clicking β€œ#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

String.split is defined as returning string[], but values in the array can be undefined. #52299

Closed
fpintos opened this issue Jan 19, 2023 Β· 3 comments
Labels
Duplicate An existing issue was already created

Comments

@fpintos
Copy link
Member

fpintos commented Jan 19, 2023

Bug Report

πŸ”Ž Search Terms

string.split undefined

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about string.split

⏯ Playground Link

Playground Link

πŸ’» Code

const [a,b] = "hello".split('@');
console.log([a,b]); // b is typed as string, but it can be undefined. a, on the other hand, is guaranteed to be string and not undefined.

// If b is passed to a function that strictly expects valid string, we get a runtime error.
// Compiler should have prevented it by detecting that b can be string|undefined.
console.log(foo(a,b));
function foo(a:string, b:string) {
    return a.length + b.length;
}

πŸ™ Actual behavior

Variable b is typed as string, when it can have an undefined value. Correct type would be string | undefined, so compiler can detect if it is being incorrectly passed to a function that strictly expects a valid string value.

πŸ™‚ Expected behavior

String.split() return type should be [string, ...(string | undefined)[]] to be correct.
This would be breaking change for programs using strict checks, but it will help catch unexpected undefined values being passed around.

Current workaround is to fix the type on every split() call:

const [a,b] = "hello".split('@') as [string, ...(string | undefined)[]];

The compiler will then flag invalid calls using b as string.
Playground Link

@whzx5byb
Copy link

String.split() return type should be [string, ...(string | undefined)[]] to be correct.

That's not true because ''.split('') returns [].

And if you want to include undefined type you can enable noUncheckedIndexedAccess.

@MartinJohns
Copy link
Contributor

Duplicate of #49635. Used search terms: split in:title

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 19, 2023
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

5 participants