You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
String.split is defined as returning string[], but values in the array can be undefined.Β #52299
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));functionfoo(a:string,b:string){returna.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:
Activity
whzx5byb commentedon Jan 19, 2023
That's not true because
''.split('')returns[].And if you want to include
undefinedtype you can enablenoUncheckedIndexedAccess.MartinJohns commentedon Jan 19, 2023
Duplicate of #49635. Used search terms:
split in:titletypescript-bot commentedon Jan 21, 2023
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.