TypeScript 中对象字面量的类型定义 [英] Type definition in object literal in TypeScript
本文介绍了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;
};
我收到以下错误:
名称字符串"在当前作用域中不存在
The name 'string' does not exist in the current scope
我做错了什么还是这是一个错误?
Am I doing something wrong or is this a bug?
推荐答案
您已经很接近了,您只需要将 =
替换为 :
.您可以使用对象类型文字(请参阅规范第 3.5.3 节)或接口.使用对象类型文字与您所拥有的很接近:
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" };
但你也可以使用接口
interface MyObjLayout {
property: string;
}
var obj: MyObjLayout = { property: "foo" };
这篇关于TypeScript 中对象字面量的类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文