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?
I know I'm late, but in the current version of TypeScript (maybe ver 2.7 and newer), you can write it like below.
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
}
}
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.
There seems to be another option as well because tsc
supports the following flag:
--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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With