Skip to content

Strict null checks with arrays #13499

Closed
Closed

Description

TypeScript Version: 2.1.5 + http://www.typescriptlang.org/play/ both with strictNullChecks enabled

Code

// A *self-contained* demonstration of the problem follows...
interface ITest {
    key: string;
    values?: number[]
}

const t: ITest[] = [
    { key: 'key1', values: [] },
    { key: 'key2', values: [] }
];

for (const i of [1, 2, 3, 4, 5, 6, 7]) {
    t[0].values.push(i);
    t[1].values.push(i);
}

Expected behavior:

Since t[0] and t[1] have initialized values, I would expect that their type is number[]

Actual behavior:

I haven't found any workaround in which case t[0].values wouldn't be marked as possibly undefined anymore. Even if I set it right before the execution:

for (const i of [1, 2, 3, 4, 5, 6, 7]) {
    t[0].values = [];
    t[0].values.push(i);
}

I'm still getting the error that values might be undefined. My ugly workaround for now is to use 2 variables. Would it be possible to fix this in future versions of typescript?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions