在打字稿中定义对象键的类型

时间:2018-07-25 13:56:35

标签: typescript class interface typescript-typings

我是TypeScript的新手,我想为对象键定义类型,我已经检查了几种实现它的方法,但是在分配不同类型的值时不会引发错误。例如

interface sectionProp { 
    _type1: String,
    _columnStrechAllowed: Boolean,
    _columnOccupancy: Number,
    is_mandatory: Boolean
}


export class sectionProperties {
  folioSectionContentProp = <sectionProp> {}

  constructor(type?) {
    this.folioSectionContentProp._type1 = type;
    this.folioSectionContentProp._columnStrechAllowed = false;
    this.folioSectionContentProp._columnOccupancy = 6;
    this.folioSectionContentProp.is_mandatory = false;
  }

}

export class createNewSection extends sectionProperties {
  constructor() {
    super("Test") // here I will assign value
 // super(12)     //@ this does not generate any error as well
 // I might assign value by some other way (from object creation) 
 // but I want to know the reason if type is defined then it should 
 // not accept any value other than type 
  }

}

var z = new createNewSection();
console.log(z)

PS:我希望定义对象键类型

谢谢

1 个答案:

答案 0 :(得分:0)

问题是您实际上没有在type的构造函数中为sectionProperties参数指定一个值,因此假定它是any,并且可以从任何内容中分配任何值,并且到任何东西。您需要一个显式的类型注释:

interface sectionProp {
    _type1: String,
    _columnStrechAllowed: Boolean,
    _columnOccupancy: Number,
    is_mandatory: Boolean
}


export class sectionProperties {
    folioSectionContentProp = <sectionProp>{}

    constructor(type: string) {
        this.folioSectionContentProp._type1 = type;
        this.folioSectionContentProp._columnStrechAllowed = false;
        this.folioSectionContentProp._columnOccupancy = 6;
        this.folioSectionContentProp.is_mandatory = false;
    }

}

export class createNewSection extends sectionProperties {
    constructor() {
        super("Test") // here I will assign value
        // super(12)     //would be an error
    }

}

您可能会考虑指定noImplicitAny编译器选项,以强制您指定编译器无法推断它们的类型。