TypeScript:对象类型的索引签名隐式具有"任何"类型

uks*_*ksz 12 typescript

我的功能有问题:

    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)

此代码可以在不更改任何编译器标志的情

  • 嗨,马丁,这个问题的答案很好,我只是想知道你(或其他任何人)是否知道为什么这样做,或者为什么我们必须定义本地的objectCopy和objectSource变量? (5认同)