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

class className {
  property: string;
};

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

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

var obj = {
  property: string;
};

我得到以下错误:

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

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


当前回答

使用type关键字创建类型

type ObjType = {
  property: string;
}

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

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

其他回答

你可以使用预定义的实用程序类型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'.
};

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

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

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

var x = { property: 'hello' };

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

只是扩展@RickLove的回复…

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

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

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

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

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

export type InitState = typeof initialState;

要小心了。这对一些人来说可能是显而易见的,但类型声明:

const foo: TypeName = {}

与as的铸造相比不一样:

const foo = {} as TypeName

尽管有人建议把它用在其他答案上。

例子:

谢谢,类型安全!:

const foo: { [K in 'open' | 'closed']: string } = {}
// ERROR: TS2739: Type '{}' is missing the following properties from type '{ open: string; closed: string; }': open, closed

再见,类型安全!:

const foo = {} as { [K in 'open' | 'closed']: string }
// No error

在你的代码中:

var obj = {
  myProp: string;
};

您实际上是在创建一个对象文字,并将变量字符串分配给属性myProp。虽然这是非常糟糕的做法,但这实际上是有效的TS代码(不要使用它!):

var string = 'A string';

var obj = {
  property: string
};

然而,你想要的是对象文字的类型。这可以通过多种方式实现:

接口:

interface myObj {
    property: string;
}

var obj: myObj = { property: "My string" };

类型别名:

type myObjType = {
    property: string
};

var obj: myObjType = { property: "My string" };

对象类型文字:

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