In TypeScript classes it\'s possible to declare types for properties, for example:
class className {
property: string;
};
How do declare
If your properties have the same type, you could use predefined utility type Record :
type Keys = "property" | "property2"
const obj: Record<Keys, string> = {
property: "my first prop",
property2: "my second prop",
};
You can of course go further and define a custom type for your property values:
type Keys = "property" | "property2"
type Values = "my prop" | "my other allowed prop"
const obj: Record<Keys, Values> = {
property: "my prop",
property2: "my second prop", // TS Error: Type '"my second prop"' is not assignable to type 'Values'.
};
In TypeScript if we are declaring object then we'd use the following syntax:
[access modifier] variable name : { /* structure of object */ }
For example:
private Object:{ Key1: string, Key2: number }
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" };