HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptCritical

Type definition in object literal in TypeScript

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescriptliteralobjectdefinitiontype

Problem

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?

Solution

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

Code Snippets

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

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

Context

Stack Overflow Q#12787781, score: 662

Revisions (0)

No revisions yet.