简体   繁体   中英

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

I can do this:

var a: number = 99;

but how can I define a when it's inside an object:

var ob = { a: 99 }

or

class AClass {

    ob = { a: 99 };

    constructor() {
    }

}

Is the only way to do this with an interface?

An interface is not required. If you just want to define the "shape" of your object, without an explicit class/interface declaration, you can do so like this:

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

In your class example, it would look like this:

class AClass {

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

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

}

This works with complex objects as well:

    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 function declaration where you know you're 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, having said that, I'd encourage you to think carefully about whether or not an interface is better suited. If this is a simple object shape, and a one-off situation that's not going to recur, declaring the shape inline (as described above) may be fine, but if you are ever going to have an object with the same shape elsewhere, it probably makes sense to declare it as an interface, then you can re-use the interface. And this is doubly-true if you are working with a complex object that goes many levels deep. It could get pretty ugly trying to do it all inline.

You could 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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