Solution: The element implicitly has type "any" because an expression of type "string" cannot be used with index type "{}". Index signature with parameter of type 'string' not found on type '{}'.

Today when I was using ts to write code, I encountered a small problem. The code is as follows:

public static objToParm(obj:object): string {
        let parm = '?';
        for (const key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                const value = obj[key];
                parm += key + '=' + value + '&';
            }
        }
        return parm.substring(0, parm.length - 1);
    }

 screenshot:

Reason for the error: The  reason for this error is that you are trying to use a string as an index into an object, but the TypeScript compiler cannot determine whether the index is valid because the object type "{}" does not define an index that accepts a string as an index. sign.

Solution: use { [key: string]: any }

代码:

public static objToParm(obj: { [key: string]: any }): string {
        let parm = '?';
        for (const key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                const value = obj[key];
                parm += key + '=' + value + '&';
            }
        }
        return parm.substring(0, parm.length - 1);
    }

That's ok

Guess you like

Origin blog.csdn.net/xiaomaomixj/article/details/132212397