Description
Search Terms
tuple, flow analysis, constant index, type narrowing
Suggestion
Currently flow analysis works for object properties, but not for tuple/array items (or even objects with explicit numeric-string-keys (obj['0']
) according to my quick experiment in the playground). It seems to me that this should at the very least work for accessing a constant index.
Putting this in code terms
function takesNumber(n: number) { }
const object: { x: number | null } = { x: 10 };
const numObject: { '0': number | null } = { '0': 10 };
const tuple: [number | null] = [10];
if (object.x) takesNumber(object.x); // OK
if (numObject['0']) takesNumber(numObject['0']); // Error
if (tuple[0]) takesNumber(tuple[0]); // Error
The numObject
case is particularly surprising to me.
Playground link (requires strict mode):
Use Cases
I hit this issue when trying to refactor:
interface Thing {
startDate: Date | undefined;
endDate: Date | undefined;
}
foo(thing: Thing) {
const asMoment = thing.startDate && moment(thing.startDate)
}
to
interface Thing {
dateRange: [Date | undefined, Date | undefined];
}
foo(thing: Thing) {
const asMoment = thing[0] && moment(thing[0])
}
Checklist
My suggestion meets these guidelines:
[x] This wouldn't be a breaking change in existing TypeScript / JavaScript code
[x] This wouldn't change the runtime behavior of existing JavaScript code
[x] This could be implemented without emitting different JS based on the types of the expressions
[x] This isn't a runtime feature (e.g. new expression-level syntax)
Potentially related issues
I don't know enough about the compiler to know whether these address the same issue.