Skip to content

Type narrowing for constant-index tuple item access #24120

Closed
@whatisaphone

Description

@whatisaphone

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):

https://www.typescriptlang.org/play/index.html#src=function%20takesNumber(n%3A%20number)%20%7B%20%7D%0D%0A%0D%0Aconst%20object%3A%20%7B%20x%3A%20number%20%7C%20null%20%7D%20%3D%20%7B%20x%3A%2010%20%7D%3B%0D%0Aconst%20numObject%3A%20%7B%20'0'%3A%20number%20%7C%20null%20%7D%20%3D%20%7B%20'0'%3A%2010%20%7D%3B%0D%0Aconst%20tuple%3A%20%5Bnumber%20%7C%20null%5D%20%3D%20%5B10%5D%3B%0D%0A%0D%0Aif%20(object.x)%20takesNumber(object.x)%3B%20%20%2F%2F%20OK%0D%0Aif%20(numObject%5B'0'%5D)%20takesNumber(numObject%5B'0'%5D)%3B%20%20%2F%2F%20Error%0D%0Aif%20(tuple%5B0%5D)%20takesNumber(tuple%5B0%5D)%3B%20%20%2F%2F%20Error%0D%0A

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

#23512
#12849
#14957

I don't know enough about the compiler to know whether these address the same issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions