Typescript – Type definition in object literal in TypeScript

typescript

In TypeScript classes it's possible to declare types for properties, for example:

class className {
  property: string;
};

How do declare the type of a property in an object literal?

I've tried the following code but it doesn't compile:

var obj = {
  property: string;
};

I'm getting the following error:

The name 'string' does not exist in the current scope

Am I doing something wrong or is this a bug?

Best Answer

You're pretty close, you just need to replace the = with a :. You can use an object type literal (see spec section 3.5.3) or an interface. Using an object type literal is close to what you have:

var obj: { property: string; } = { property: "foo" };

But you can also use an interface

interface MyObjLayout {
    property: string;
}

var obj: MyObjLayout = { property: "foo" };