Closed as not planned
Closed as not planned
Description
π Search Terms
#52299 (closed)
#30406 (marked as design limitation)
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β Suggestion
In es5.d.ts
before:
interface String {
split(separator: string | RegExp, limit?: number): string[];
}
after:
interface String {
split<S extends string>(separator: S): string extends S ? string[] :
S extends "" ? string[] : [string, ...string[]];
split(separator: string | RegExp, limit?: number): string[];
}
π Motivating Example
@noUncheckedIndexAccess: true
function checkField(fieldName: string){
let firstPathPart = fieldName;
if (fieldName.includes('.')) {
const partParts = fieldName.split('.');
firstPathPart = partParts[0]; // error
}
}
π» Use Cases
- What do you want to use this for?
As shown above
- What shortcomings exist with current approaches?
As shown above.
- What workarounds are you using in the meantime?
@noUncheckedIndexAccess: true
interface String {
split<S extends string>(separator: S): string extends S ? string[] :
S extends "" ? string[] : [string, ...string[]];
split(separator: string | RegExp, limit?: number): string[];
}
function checkField(fieldName: string){
let firstPathPart = fieldName;
if (fieldName.includes('.')) {
const partParts = fieldName.split('.');
firstPathPart = partParts[0]; // no error
}
}
{
// #53362 & #56332 & #56333 all give these results
const x1 = "".split('.'); // [string, ...string[]]
const x10 = x1[0]; // string
const x11 = x1[1]; // string | undefined
const x31 = "".split('.')[0]; // string
const x32 = "".split('.')[1]; // string | undefined
const x4 = "".split(''); // string[]
const x5 = "".split((0 as any as string)); // string[]
}
[playground](https://www.typescriptlang.org/play?#code/FDCWDsBcFMCcDMCGBjaACAypWEDmaBvYNEtAZwAcAbUSAHgzWgA8ZwATM87PAPgAoy0ColiJIAe1gAuTAEpZZHuHws2nTGgD83HCoDaAXTSzipc4zXQOXAES3tuvEZNp9SvbgA0aAHT+PZ0NDAG4zEkoaSEFhUXEpRWV8AB80ACVoXABRZgofGgBbWi1ZcABXAoAjOAUnA1DgAF8QeDLwZEhQCXA0ZAALaGQAawAxUGgqdn54ccmAOUQC6ETPOSJzKmhINBnYJQAFcT7D2G2AXh3Z9gWlsPNQeDRpq5voXwhkKjL2aDJ+AHJfP85HJCOFzL1uko0CJTidIFwLjMJtdFm9IrQAUC5HcISRdgcjvC0BdYZB4WR9AAGUJoAD0dLQ4AkTFgsCk4OazWAyCh22YAEYSWh7L4MdFAcCQvTGW5AiofP4xUkjIYeXy0MwAEzCwXU2kMuq4dXgaHMADMwtF4qxwP10sN8uNvNN-IALFbbGLqJj-lKZUajCazQBWT3eqL8fhUtCILiIcAAT1jXCdIIdjKdQaAA)