在TypeScript类中,可以为属性声明类型,例如:

class className {
  property: string;
};

如何在对象文字中声明属性的类型?

我已经尝试了以下代码,但它不能编译:

var obj = {
  property: string;
};

我得到以下错误:

名称“string”在当前作用域中不存在

是我做错了什么还是这是个bug?


当前回答

只是扩展@RickLove的回复…

这很好,因为你只需要定义不能推断的类型:

const initialState = { 
   user: undefined as User | undefined, 
   userLoading: false
}; 

它被编译成下面的js代码:

const initialState = { 
   user: undefined, 
   userLoading: false
};  

如果你需要把它提取成一个类型,你可以这样做:

export type InitState = typeof initialState;

其他回答

在TypeScript中,如果我们声明object,那么我们将使用以下语法:

[access modifier] variable name : { /* structure of object */ }

例如:

private Object:{ Key1: string, Key2: number }

如果你试图写一个类型注释,语法是:

var x: { property: string; } = { property: 'hello' };

如果你试图写一个对象文字,语法是:

var x = { property: 'hello' };

您的代码试图在值位置使用类型名称。

你已经很接近了,你只需要用a:替换=。您可以使用对象类型文字(参见规范第3.5.3节)或接口。使用对象类型文字接近于你所拥有的:

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

但是你也可以使用接口

interface MyObjLayout {
    property: string;
}

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

我很惊讶没有人提到这一点,但你可以创建一个名为ObjectLiteral的接口,它接受类型string: any的键:值对:

interface ObjectLiteral {
  [key: string]: any;
}

然后你可以这样使用它:

let data: ObjectLiteral = {
  hello: "world",
  goodbye: 1,
  // ...
};

一个额外的好处是,您可以根据需要在任意多个对象上多次重用该接口。

祝你好运。

只是扩展@RickLove的回复…

这很好,因为你只需要定义不能推断的类型:

const initialState = { 
   user: undefined as User | undefined, 
   userLoading: false
}; 

它被编译成下面的js代码:

const initialState = { 
   user: undefined, 
   userLoading: false
};  

如果你需要把它提取成一个类型,你可以这样做:

export type InitState = typeof initialState;