无法设置未定义TypeScript的属性

时间:2017-12-19 14:46:06

标签: typescript

我想用数据设置对象,然后将其推送到另一个对象

let globalSamples = {} as any;
let sample = { } as ISamplesDetail [];
sample = [];
for (let i = 0 ; i<this.prelevementLingette.samplesDetail.length; i++)
    {
      sample [i].id= this.old.samplesDetail[i].id;
      sample [i].reference=this.old.samplesDetail[i].reference;
}
globalSamples.push(sample);

我收到此错误'Cannot set property 'reference' of undefined'

如何解决问题?

1 个答案:

答案 0 :(得分:1)

您的代码中存在一些问题,所以我已将其清理了一下

// looks like this would be a proper type..
const globalSamples: ISamplesDetail[][] = [];

// can't assign object ({}) what should be an array, so..
// value doesn't change -> const
const sample: ISamplesDetail[] = [];


// it's strange that you iterate over 'this.prelevementLingette',
// but access 'this.old'
for (let i = 0 ; i < this.prelevementLingette.samplesDetail.length; i++) {
      sample[i] = {
          id: this.old.samplesDetail[i].id,
          reference: this.old.samplesDetail[i].reference
      }
}

// can't push to an object (should be array - [])
globalSamples.push(sample);

您的代码中的逻辑似乎有点扭曲,但在不了解上下文的情况下很难说