简体   繁体   中英

Using bracket notation with a variable to access object property returns undefined

I'm relatively new to TypeScript and I'm confused about why using bracket notation on an object with variable as a key always returns undefined . I have an object defined that looks something like,

{
    "data": {
        "text": "hello"
    } 
}

that I import into my code using something like import * as myBlob from./data.json . When I access the the data key of myBlob using the bracket notation with a string literal as key ( myBlob['data'] ), it works as expected. However, this access pattern returns undefined :

let key = 'data';
myBlob[key]; //undefined

I hope someone can enlighten me on why this is happening.

Do this:

import * as importedMyBlob from./data.json

Then use it like the following:

const myBlob = importedMyBlob.default;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM