Dace Zarina Dace Zarina - 1 month ago 20
TypeScript Question

Type definition in object literal in TypeScript

In TypeScript in class it is possible to declare type for property, for example:

class className{
property : string;

How should I write code to declare type for property in object literal? Such code don't compile:

var obj = {
property: string;

(I am getting error - The name 'string' does not exist in the current scope).

What I am doing wrong or it is a bug?


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" };