error TS2339: Property 'x' does not exist on type 'Y'

前端 未结 6 1214
忘掉有多难
忘掉有多难 2020-12-01 12:02

I don\'t understand why this code generates TypeScript error. (It\'s not the original code and is a bit derived, so please ignore the non-sense in the example):



        
6条回答
  •  感动是毒
    2020-12-01 12:16

    I'm no expert in Typescript, but I think the main problem is the way of accessing data. Seeing how you described your Images interface, you can define any key as a String.

    When accessing a property, the "dot" syntax (images.main) supposes, I think, that it already exists. I had such problems without Typescript, in "vanilla" Javascript, where I tried to access data as:

    return json.property[0].index

    where index was a variable. But it interpreted index, resulting in a:

    cannot find property "index" of json.property[0]

    And I had to find a workaround using your syntax:

    return json.property[0][index]

    It may be your only option there. But, once again, I'm no Typescript expert, if anyone knows a better solution / explaination about what happens, feel free to correct me.

提交回复
热议问题