Skip to content

Object is possibly undefined` error in TypeScript 4.1.2 #41612

Closed
@doberkofler

Description

@doberkofler

TypeScript Version: 4.1.2

Search Terms: Object is possibly undefined

Code

function main(values: Array<string>) {
    for (let i = 0; i < values.length; i++) {
        if (typeof values[i] === 'string' && values[i].length > 0) {
            console.log(i);
        }
    }
}

Expected behavior:
No error

Actual behavior:
TypeScript 4.1.2 reports a Object is possibly undefined error in values[i].length but given the first condition the object must be defined as it is of type 'string'

Playground Link: https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&ts=4.1.0-beta#code/GYVwdgxgLglg9mABAWwIYzACgG6oDYgCmAzgFyICCATlagJ4A8xUVGA5gHwCUiA3gFCIhiYHCqJMeQlEQxEAXkQAGANyzEDRLgIkAdFLBsoACzUwA1OZ4Dht2cAlQ6AB0JwH2osQDaMALoK8ooA5MyshsGIAGRRWvhevn76hIYmiBzK1oJ2ORAIxHBS+nBsmDBcKtk5AL5ViLW1QA

Related Issues: no

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions