在TypeScript类中,可以为属性声明类型,例如:
class className {
property: string;
};
如何在对象文字中声明属性的类型?
我已经尝试了以下代码,但它不能编译:
var obj = {
property: string;
};
我得到以下错误:
名称“string”在当前作用域中不存在
是我做错了什么还是这是个bug?
在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;
其他回答
这是我在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游乐场
只是扩展@RickLove的回复…
这很好,因为你只需要定义不能推断的类型:
const initialState = {
user: undefined as User | undefined,
userLoading: false
};
它被编译成下面的js代码:
const initialState = {
user: undefined,
userLoading: false
};
如果你需要把它提取成一个类型,你可以这样做:
export type InitState = typeof initialState;
在你的代码中:
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" };
用DRY将对象文字转换为类型
只做:
const myObject = {
hello: 'how are you',
hey: 'i am fine thank you'
}
type myObjectType = keyof typeof MyObject
完成工作!
使用type关键字创建类型
type ObjType = {
property: string;
}
然后,您可以使用它来绑定您的对象,以只接受这种类型,如下所示。
const obj: ObjType = {
property: "TypeScript"
}