【问题标题】:Define types for object keys in typescript在打字稿中定义对象键的类型
【发布时间】:2019-01-02 09:11:19
【问题描述】:

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

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:我想定义我的对象键类型

谢谢

【问题讨论】:

    标签: typescript class interface typescript-typings


    【解决方案1】:

    问题是你实际上并没有在sectionProperties 的构造函数中为type 参数指定一个值,所以它被假定为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 编译器选项来强制您指定编译器无法推断的类型。

    【讨论】:

    • 感谢您的回答,如果我们在构造函数中显式定义类型而不是我们需要接口(我们在其中定义键的类型)?我希望我不会将两者混为一谈。因为如果我们为 sectionProperties 构造函数定义类型,那么这种情况只会在那里处理。
    • @Mohd.Monis 不确定我明白你想说什么。 sectionProp 中的 type1 字段是一个字符串。是否要在派生类型(例如createNewSection )中使用从sectionProp 派生的不同类型?
    • 如果我分配这样的值 z.folioSectionContentProp._type1 = 12 ;它会产生错误,这就是我所需要的。我将两者与构造函数调用混合在一起,而不是检查类型,并将类型放入构造函数中进行检查,所以我认为接口的用途是什么。我现在得到了这个。谢谢
    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2021-03-04
    • 2021-12-16
    • 1970-01-01
    • 2020-01-17
    • 2017-01-16
    相关资源
    最近更新 更多