TypeError:无法读取属性'替换'在实例化对象时未定义

时间:2017-04-06 06:16:24

标签: typescript

这是我的课程和界面:

export interface Foo{
    numFoo: string
}

export class Blah{
  constructor(
    public numBlah: string,
    public arrayOfFoos: Array<Foo>,
    public idBlah: string
    ) { }
}

let numBlah: string = 'numBlah'
let arr: Array<Foo> =[{numFoo: '1'}]
let idBlah: string = 'id'
let blah = new Blah(numBlah, arr, idBlah)

我只希望通过直接传递参数来实例化一个新的Blah项(不提及字段的名称)。知道我为什么会遇到这个错误吗?

1 个答案:

答案 0 :(得分:0)

尝试将代码重新格式化为旧式OOP版本:

export interface Foo {
    numFoo: string;
}

export class Blah {

    public numBlah: string;
    public arrayOfFoos: Foo[];
    public idBlah: string;

    constructor (numBlah: string, arrayOfFoos: Foo[], idBlah: string) {
        this.numBlah = numBlah;
        this.arrayOfFoos = arrayOfFoos;
        this.idBlah = idBlah;
    }

}

let numBlah: string = 'numBlah';
let arr: Foo[] = [{ numFoo: '1' }];
let idBlah: string = 'id';

let blah = new Blah(numBlah, arr, idBlah);

console.log(blah.idBlah);