0

什么时候

function StyleMixin(base: React.CSSProperties) {}




StyleMixin({
    fontWeight: 'bold',
    lineHeight: 1,
    textAlign: 'center',
    [someVariable]: {
        fontSize: '1rem',
    }
}

[someVariable]中,它说

TS2345:类型参数 '{ fontWeight: "bold"; 线高:数字;文本对齐:“中心”;...' 不能分配给“CSSProperties”类型的参数。对象字面量只能指定已知属性,并且“[someVariable]”类型不存在于“CSSProperties”中。

如何解决这个问题?

4

1 回答 1

2

如果someVariable字符串文字类型不是React.CSSProperties

const someVariable = "nonExistentProperty";
StyleMixin({
    fontWeight: 'bold',
    lineHeight: 1,
    textAlign: 'center',
    [someVariable]: {
        fontSize: '1rem',
    }
})

如果someVariable是变量而不是常量(即用letor声明var),它实际上会起作用。

我建议确保您确实想要添加一个不在其中的属性CSSProperties(如果您没有看到"noErrorTruncation": true在 tsconfig.json 中使用的完整错误消息)

如果你真的想StyleMixin成为一个可以添加额外属性的对象,CSSProperties你可以在函数中使用泛型参数:

function StyleMixin< T extends React.CSSProperties>(base: T) {}
const someVariable = "nonExistentProperty";
StyleMixin({
    fontWeight: 'bold',
    lineHeight: 1,
    textAlign: 'center',
    [someVariable]: {
        fontSize: '1rem',
    }
})
于 2018-08-16T11:45:40.490 回答