我的功能有问题:
copyObject(object:T):T { var objectCopy = {}; for (var key in object) { if (object.hasOwnProperty(key)) { objectCopy[key] = object[key]; } } return objectCopy; }
我有以下错误:
Index signature of object type implicitly has an 'any' type.
我该如何解决?
class test{ copyObject (object:T):T { var objectCopy = {}; for (var key in object) { if (object.hasOwnProperty(key)) { objectCopy[key] = object[key]; } } return objectCopy; } }
如果我按如下方式运行代码
c:\Work\TypeScript>tsc hello.ts
它运作正常.但是,以下代码:
c:\Work\TypeScript>tsc --noImplicitAny hello.ts
投
hello.ts(6,17): error TS7017: Index signature of object type implicitly has an 'any' type. hello.ts(6,35): error TS7017: Index signature of object type implicitly has an 'any' type.
因此,如果禁用noImplicitAny
标志,它将起作用.
似乎还有另一个选项,因为tsc
支持以下标志:
--suppressImplicitAnyIndexErrors Suppress noImplicitAny errors for indexing objects lacking index signatures.
这对我也有用:
tsc --noImplicitAny --suppressImplicitAnyIndexErrors hello.ts
更新:
class test{ copyObject (object:T):T { let objectCopy:any = {}; let objectSource:any = object; for (var key in objectSource) { if (objectSource.hasOwnProperty(key)) { objectCopy[key] = objectSource[key]; } } return objectCopy; } }
此代码可以在不更改任何编译器标志的情