在TypeScript类中,可以声明属性的类型,例如:
class className {
property: string;
};
如何在对象文字中声明属性的类型?
我尝试了以下代码,但它不能编译:
var obj = {
property: string;
};
我得到以下错误:
名称'string‘在当前作用域中不存在
是我做错了什么,还是这是个bug?
发布于 2012-10-09 03:08:38
已经很接近了,只需要用:
替换=
即可。您可以使用对象类型文字(参见规范3.5.3节)或接口。使用对象类型文字与您所拥有的非常接近:
var obj: { property: string; } = { property: "foo" };
但是您也可以使用一个接口
interface MyObjLayout {
property: string;
}
var obj: MyObjLayout = { property: "foo" };
发布于 2012-10-11 12:50:13
更新2019-05-15 (改进的Code Pattern作为替代方案)
在使用const
多年并受益于更多的函数代码之后,我建议在大多数情况下不要使用下面的代码。(在构建对象时,强制将类型系统转换为特定类型,而不是让它推断类型,这通常是出了问题的迹象)。
相反,我建议尽可能多地使用const
变量,然后将对象组合为最后一步:
const id = GetId();
const hasStarted = true;
...
const hasFinished = false;
...
return {hasStarted, hasFinished, id};
相加2020-02-26
如果您确实需要一个可以延迟初始化的类型:请标记它是一个可以为null的联合类型(null或Type)。类型系统将阻止您在未首先确保它具有值的情况下使用它。
在tsconfig.json
中,确保启用严格的null检查:
"strictNullChecks": true
然后使用此模式,并允许类型系统保护您免受意外的空/未定义访问:
const state = {
instance: null as null | ApiService,
// OR
// instance: undefined as undefined | ApiService,
};
const useApi = () => {
// If I try to use it here, the type system requires a safe way to access it
// Simple lazy-initialization
const api = state?.instance ?? (state.instance = new ApiService());
api.fun();
// Also here are some ways to only access it if it has value:
// The 'right' way: Typescript 3.7 required
state.instance?.fun();
// Or the old way: If you are stuck before Typescript 3.7
state.instance && state.instance.fun();
// Or the long winded way because the above just feels weird
if (state.instance) { state.instance.fun(); }
// Or the I came from C and can't check for nulls like they are booleans way
if (state.instance != null) { state.instance.fun(); }
// Or the I came from C and can't check for nulls like they are booleans
// AND I was told to always use triple === in javascript even with null checks way
if (state.instance !== null && state.instance !== undefined) { state.instance.fun(); }
};
class ApiService {
fun() {
// Do something useful here
}
}
在99%的情况下,不要执行以下操作:
更新2016-02-10 -处理TSX (谢谢@Josh)
对TSX使用as
运算符。
var obj = {
property: null as string
};
一个更长的例子:
var call = {
hasStarted: null as boolean,
hasFinished: null as boolean,
id: null as number,
};
原始答案
使用cast操作符使其简洁(通过将null转换为所需的类型)。
var obj = {
property: <string> null
};
一个更长的例子:
var call = {
hasStarted: <boolean> null,
hasFinished: <boolean> null,
id: <number> null,
};
这比有两个部分(一个声明类型,第二个声明默认值)要好得多:
var callVerbose: {
hasStarted: boolean;
hasFinished: boolean;
id: number;
} = {
hasStarted: null,
hasFinished: null,
id: null,
};
发布于 2019-05-20 16:56:05
我很惊讶没有人提到这一点,但您可以只创建一个名为ObjectLiteral
的接口,它接受类型为string: any
的key: value
对
interface ObjectLiteral {
[key: string]: any;
}
然后使用它,如下所示:
let data: ObjectLiteral = {
hello: "world",
goodbye: 1,
// ...
};
一个额外的好处是,您可以根据需要在任意多个对象上多次重用此接口。
祝好运。
https://stackoverflow.com/questions/12787781
复制相似问题