TypeScript:对象类型的索引签名隐式具有“任何”类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34509636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript: Index signature of object type implicitly has an 'any' type
提问by uksz
I am having an issue with my function:
我的功能有问题:
copyObject<T> (object:T):T {
var objectCopy = <T>{};
for (var key in object) {
if (object.hasOwnProperty(key)) {
objectCopy[key] = object[key];
}
}
return objectCopy;
}
And I have following error:
我有以下错误:
Index signature of object type implicitly has an 'any' type.
How can I fix it?
我该如何解决?
回答by Martin Vseticka
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;
}
}
If I run the code as follows
如果我按如下方式运行代码
c:\Work\TypeScript>tsc hello.ts
it works OK. However, the following code:
它工作正常。但是,以下代码:
c:\Work\TypeScript>tsc --noImplicitAny hello.ts
throws
投掷
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.
So if you disable noImplicitAny
flag, it will work.
因此,如果您禁用noImplicitAny
标志,它将起作用。
There seems to be another option as well because tsc
supports the following flag:
似乎还有另一种选择,因为tsc
支持以下标志:
--suppressImplicitAnyIndexErrors Suppress noImplicitAny errors for indexing objects lacking index signatures.
This works for me too:
这也适用于我:
tsc --noImplicitAny --suppressImplicitAnyIndexErrors hello.ts
Update:
更新:
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;
}
}
This code works without changing any compiler flags.
此代码无需更改任何编译器标志即可工作。
回答by user3562698
I know I'm late, but in the current version of TypeScript (maybe ver 2.7 and newer), you can write it like below.
我知道我迟到了,但是在当前版本的 TypeScript(可能是 2.7 版和更新版本)中,您可以像下面这样编写它。
for (var key in object) {
if (objectSource.hasOwnProperty(key)) {
const k = key as keyof typeof object;
objectCopy[k] = object[k]; // object and objectCopy need to be the same type
}
}