不要使用对象作为类型

don't use object as a type

我收到 lint 错误:

don't use object as a type

当我使用对象作为类型时,示例如下:

export const myFunc = (obj: object): string => {
  return obj.toString()
}

知道我应该为具有未知属性的对象指定什么类型吗?

如果有帮助,所讨论的对象不是数组(我知道它在 JS 中严格来说是一个对象)

提前致谢

有几种不同的方法可以做到这一点。一般来说我觉得需要这个有点反模式。

但我可能会选择 Record<string, any>,如果可以的话。

我认为最好的方法是使用泛型:

export const myFunc = <T extends { toString: () => string }>(obj: T): string => {
    return obj.toString()
}

myFunc(2) // no error
myFunc({}) // no error

如果您只想将参数限制为对象,那么是的,@Evert 的解决方案就可以了。 但为了类型安全,最好使用 unknown 而不是 any:

Record<string, unknown>

以下是为什么 linter 规则建议不要使用 object 类型的具体示例:

function foo(obj: object) {
    for (const key in obj) {
        const val = obj[key]; // Compilation error: type 'string' can't be used to index type '{}'
    }
}

function bar(obj: { [key: string]: unknown }) {
    for (const key in obj) {
        const val = obj[key]; // works :)
    }
}