繁体   English   中英

我是否必须使用接口来使用typescript定义对象的元素?

[英]Do I have to use an interface to define the elements of an object with typescript?

我可以做这个:

var a: number = 99;

但我怎么能定义a当它是一个对象中:

var ob = { a: 99 }

要么

class AClass {

    ob = { a: 99 };

    constructor() {
    }

}

使用界面是唯一的方法吗?

不需要接口。 如果你只想定义对象的“形状”,而没有显式的类/接口声明,你可以这样做:

var ob: { a:number } = {a: 99};

在您的类示例中,它看起来像这样:

class AClass {

    ob: { a:number } = { a: 99 };

    constructor() {
      // tsc knows that this.ob.a is of type number
    }

}

这也适用于复杂的对象:

    var ob: {
        a:number;
        b: {
            stringVal:string;
            numero:number;
            bitflag:Boolean
        }
    } = {
        a: 99,
        b: {
            stringVal: "Some string value here",
            numero:1234,
            bitflag:true
        }
    };

在您知道您期望具有特定属性的对象的函数声明中,此语法非常有用:

function(someObject: {stringVal:string; numero:number})
    // TypeScript now knows that someObject will have a "stringVal" string property, and a "numero" number property
}

现在,说了这些,我建议你仔细考虑界面是否更适合。 如果这是一个简单的物体形状,这不会再发生一次性的情况下,宣布形状的内联(如上所述)可能被罚款,但如果你曾经打算具有相同形状的物体在其他地方,它将它声明为接口可能是有意义的,然后您可以重新使用该接口。 如果你正在处理一个深层次的复杂对象,这是双重的。 尝试全部内联可能会变得非常丑陋。

你可以定义一个这样的类:

var a: number = 99;

class Ob{
    constructor(public a: number){}
}

var newOb = new Ob(a);
newOb.a // should equal 99 then.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM