这是我的代码的一部分:
const myObj: object = {}
const propname = 'propname'
myObj[propname] = 'string'
但是我得到了错误:
ERROR in path/to/file.ts(4,1)
TS7053: Element implicitly has an 'any' type because expression of type '"propname"' can't be used to index type '{}'.
Property 'propname' does not exist on type '{}'.
这里出了什么问题,我该如何修复它?
您必须定义对象具有哪种索引类型。在你的情况下,它是一个基于
string
的索引。
const myObj: {[index: string]:any} = {}
下面是一些解决通过数组访问访问属性时出现“
TS7053 Element implicitly has an 'any' type
”错误的解决方案。
原始代码:
const myObj: object = {}
const prop = 'propname'
myObj[prop] = 'string' // Error!
注意:这不起作用,因为索引签名仍然未定义:
const myObj: {propname: any} = {}
const prop = 'propname'
myObj[prop] = 'string' // Error!
解决方案1:隐式定义索引签名
const myObj: {[key: string]: any} = {}
const prop = 'propname'
myObj[prop] = 'string'
解决方案2:使用接口提供索引签名
interface IStringIndex {
[key: string]: any
}
const myObj: IStringIndex = {}
const prop = 'propname'
myObj[prop] = 'string'
<Record>
实用程序类型:
interface IStringIndex extends Record<string, any> {}
const myObj: IStringIndex = {}
const prop = 'propname'
myObj[prop] = 'string'
解决方案 4:使用索引签名定义类型别名
type MyObject = {
[key: string]: any
propname?: any
}
const myObj: MyObject = {}
const prop = 'propname'
myObj[prop] = 'string'
解决方案 5:描述索引签名的接口和描述有效属性的类型别名的组合:
interface IStringIndex extends Record<string, any> {}
type MyObject = IStringIndex & {
propname?: string
}
const myObj: MyObject = {}
const prop = 'propname'
myObj[prop] = 'string'
解决方案 6:定义有效(字符串)属性名称列表:
type ValidProps = 'propname' | 'value'
interface IStringIndex extends Record<ValidProps, any> {}
const myObj: IStringIndex = {
propname: 'my prop',
value: 123
}
const prop = 'propname'
myObj[prop] = 'string'
注意:分配对象时,ValidProps
列表中的所有属性都必须存在!
keyof
,如下所示:
interface SomeInterface {
propertyA: string;
propertyB: string;
}
const object: SomeInterface = {propertyA: 'A', propertyB: 'B'};
for ( const prop in object ) {
const value = object[prop]; // <-- will throw an error
const typedValue = object[prop as keyof SomeInterface]; // <-- will do fine
}
否则,您可以通过向要通过的接口/类添加泛型属性来“破解”它,但它为类型不安全打开了一扇完全不同的门:)
interface SomeInterface {
propertyA: string;
propertyB: string;
[key: string]: any;
}
const propname = 'foo';
(myObj as any)[propname] = 'baz';
"compilerOptions": {
"noImplicitAny": false,
}
const listOfArray: Array<any> = [];
for(const Id in MyObject)
{
listOfArray.push(dataList[Id]);//TS7053 Error here -- Fixed by doing above things
}
当我尝试推送来自 MyObject [{Id: value 1},{Id: 2},{Id: 3}]
的结果时,面临同样的错误。
const myObj = new Map();
myObj.set('propname', "something");
const propname = 'propname'
myObj.get(propname)
在旧版本的 Ionic 中就足够了:
var jsonMessage: JSON;
在较新的版本中我必须使用:
var jsonMessage: {"type": string, "data": string};
或
var jsonMessage: {"type": any, "data": any};
keyof typeof yourObject
const haha = {
id: "string",
accountId: "string",
firstName: "string",
lastName: "string",
};
Object.keys(haha).map((k) => haha[k as keyof typeof haha]);