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

class className {
  property: string;
};

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

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

var obj = {
  property: string;
};

我得到以下错误:

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

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


当前回答

这是我在2021年用TypeScript 4.5做的事情:

const sm = {
  reg: {} as ServiceWorkerRegistration,
  quantum: null as number | null,
  currentCacheName: '' as string, // superfluous
  badSWTimer: 0 as number, // superfluous
}

这不仅仅是一个值转换,对于对象属性来说,它的工作原理与接口定义相同。

更新:我包含了两个多余的类型作为示例。也就是说,这些类型可以自动推断,因此不会产生编译器错误。

来源:4.4游乐场

其他回答

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

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

但是你也可以使用接口

interface MyObjLayout {
    property: string;
}

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

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

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

例如:

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

如果你试图向一个解构对象字面量添加类型,例如在函数的参数中,语法是:

function foo({ bar, baz }: { bar: boolean, baz: string }) {
  // ...
}

foo({ bar: true, baz: 'lorem ipsum' });

你可以使用预定义的实用程序类型Record<Keys, type >:

const obj: Record<string, string> = {
  property: "value",
};

它允许为你的对象文字指定键:

type Keys = "prop1" | "prop2"

const obj: Record<Keys, string> = {
  prop1: "Hello",
  prop2: "Aloha",
  something: "anything" // TS Error: Type '{ prop1: string; prop2: string; something: string; }' is not assignable to type 'Record<Keys, string>'.
                        //   Object literal may only specify known properties, and 'something' does not exist in type 'Record<Keys, string>'.
};

属性值的类型:

type Keys = "prop1" | "prop2"
type Value = "Hello" | "Aloha"

const obj1: Record<Keys, Value> = {
  prop1: "Hello",
  prop2: "Hey", // TS Error: Type '"Hey"' is not assignable to type 'Value'.
};

使用type关键字创建类型

type ObjType = {
  property: string;
}

然后,您可以使用它来绑定您的对象,以只接受这种类型,如下所示。

const obj: ObjType = {
property: "TypeScript"
}