Should I use an interface to define the elements of an object using typescript?

I can do it:

var a: number = 99;

      

but how can I detect a

when it is inside an object:

var ob = { a: 99 }

      

or

class AClass {

    ob = { a: 99 };

    constructor() {
    }

}

      

Is this the only way to do it using the interface?

+3


source to share


2 answers


No interface required. If you just want to define the "shape" of your object, without explicitly declaring the class / interface, you can do it like this:

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

In your example class, it would look like this:

class AClass {

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

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

}

      

This also works with complex objects:



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

      

This syntax can be useful in a function declaration where you know you are expecting an object with specific properties:

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

      

Now that having said that, I would encourage you to think carefully about whether an interface is better suited. If it's a simple object shape and a one-off situation that won't repeat itself, an inline form declaration (as described above) might be fine, but if you ever have an object with the same shape elsewhere, it probably makes sense to declare it as an interface then you can reuse the interface. And this is doubly true if you are working with a complex object that has many levels. It can get pretty ugly trying to make it all inline.

+3


source


You can define a class like this:



var a: number = 99;

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

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

      

0


source







All Articles