Should I use an interface to define the elements of an object using typescript?
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.
source to share