Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Index signature of object type implicitly has an 'any' type

Tags:

typescript

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?

like image 473
uksz Avatar asked Dec 29 '15 11:12

uksz


2 Answers

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
    }
}
like image 64
user3562698 Avatar answered Nov 15 '22 21:11

user3562698


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.

like image 40
Martin Vseticka Avatar answered Nov 15 '22 21:11

Martin Vseticka