我的功能有问题:
copyObject<T> (object:T):T {
var objectCopy = <T>{};
for (var key in object) {
if (object.hasOwnProperty(key)) {
objectCopy[key] = object[key];
}
}
return objectCopy;
}
Run Code Online (Sandbox Code Playgroud)
我有以下错误:
Index signature of object type implicitly has an 'any' type.
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
Mar*_*cka 16
class test<T> {
copyObject<T> (object:T):T {
var objectCopy = <T>{};
for (var key in object) {
if (object.hasOwnProperty(key)) {
objectCopy[key] = object[key];
}
}
return objectCopy;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我按如下方式运行代码
c:\Work\TypeScript>tsc hello.ts
Run Code Online (Sandbox Code Playgroud)
它运作正常.但是,以下代码:
c:\Work\TypeScript>tsc --noImplicitAny hello.ts
Run Code Online (Sandbox Code Playgroud)
投
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.
Run Code Online (Sandbox Code Playgroud)
因此,如果禁用noImplicitAny标志,它将起作用.
似乎还有另一个选项,因为tsc支持以下标志:
--suppressImplicitAnyIndexErrors Suppress noImplicitAny errors for indexing objects lacking index signatures.
Run Code Online (Sandbox Code Playgroud)
这对我也有用:
tsc --noImplicitAny --suppressImplicitAnyIndexErrors hello.ts
Run Code Online (Sandbox Code Playgroud)
更新:
class test<T> {
copyObject<T> (object:T):T {
let objectCopy:any = <T>{};
let objectSource:any = object;
for (var key in objectSource) {
if (objectSource.hasOwnProperty(key)) {
objectCopy[key] = objectSource[key];
}
}
return objectCopy;
}
}
Run Code Online (Sandbox Code Playgroud)
此代码可以在不更改任何编译器标志的情
| 归档时间: |
|
| 查看次数: |
15320 次 |
| 最近记录: |