属性与索引签名不兼容

sag*_*tha 7 typescript

const test = [
    {
        "a": 1
    },
    {
        "b": 1
    }
]
interface t {
    [key: string]: number
}
const ttt: t[] = test
Run Code Online (Sandbox Code Playgroud)

属性“b”与索引签名不兼容。类型 'undefined' 不能分配给类型 'number'。如果我将密钥重命名为 b 或 a 两个相同的密钥,它会起作用。

Nic*_*rdy 6

因为test没有类型,它被推断为这种类型:

({ a: number; b?: undefined; } | { b: number; a?: undefined; })[]
Run Code Online (Sandbox Code Playgroud)

test然后分配给ttt,但b在新界面中具有可能未定义的键是不兼容的t

您可以通过将类型直接添加到test以下内容来解决此问题:

const test: t[] = [
    {
        "a": 1
    },
    {
        "b": 1
    }
]
Run Code Online (Sandbox Code Playgroud)