Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typescript does not check type of mapped variable correctly. #34991

Closed
McDic opened this issue Nov 8, 2019 · 3 comments
Closed

Typescript does not check type of mapped variable correctly. #34991

McDic opened this issue Nov 8, 2019 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@McDic
Copy link

McDic commented Nov 8, 2019

TypeScript Version: 3.7.x-dev.201xxxxx

Search Terms: ts2531 possibly null

Code

interface test2{
    [key: string]: number | null
}

var obj: test2 = {
    aaa: 1234,
    bbb: null,
    ccc: -5.67
}

function check2(obj: test2, key: string){
    if(typeof obj[key] === 'number' && obj[key] !== null){
        console.log(`ok obj[key] + 10 = ${obj[key] + 10}`)
    }
    else{
        console.log('ok otherwise')
    }
}

for(const key in obj){
    check2(obj, key)
}

var a: unknown;

function check3(a: unknown): any{
    if(typeof a === 'number'){
        return a + 10;
    }
}

Expected behavior: No error

Actual behavior: TS2531 happened on function check2's console logging code. (${obj[key] + 10})

Playground Link: Here

Related Issues: #28131

@MartinJohns
Copy link
Contributor

Duplicate of #10530. Type narrowing does not occur for indexed access forms e[k] where k is not a literal.

You can solve it by just storing the value in a variable:

const value = obj[key];
if(typeof value === 'number' && value !== null){
    console.log(`ok obj[key] + 10 = ${value + 10}`)
}

@fatcerberus
Copy link

fatcerberus commented Nov 8, 2019

Type narrowing does not occur for indexed access forms e[k] where k is not a literal.

See also #31445 and #34867. At present, the compiler can't safely narrow these expressions because it only cares about the types and doesn't track the specific k variable used. test2[string] casts too wide a net to serve as a type guard.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Nov 8, 2019
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

5 participants