无法动态设置接口对象的属性值

皇家空军

我有以下代码:

interface MyType {
    a: string;
    b: number;
}

class SomeClass {
    // ... more things going on

    beta: MyType = {a: 'Lorem', b: 3};

    myFunction(alpha: MyType) {
        // beta is an object of type MyType
        for (const key in alpha) {
            this.beta[key as keyof typeof this.beta] = alpha[key as keyof typeof alpha] ?? '';
        }
    }
}

在这里看到相同的操场

但是,这会产生错误:

Element implicitly has an 'any' type because expression of type 'string | number | symbol' can't be used to index type 'MyType'.
  No index signature with a parameter of type 'string' was found on type 'MyType'.

我已经尝试了很长时间,对其进行了调整,但它仍然不起作用——我不知道为什么。keyof typeof this.beta为了简单起见,我使用它,但keyof MyType也不起作用)。

我在这里先向您的帮助表示感谢。

约塞连船长

我相信这个问题与您的问题非常相似。

考虑这个例子:

interface MyType {
    a: string;
    b: number;
}

class SomeClass {
    beta: MyType = { a: 'Lorem', b: 3 };

    myFunction(alpha: MyType) {
        // beta is an object of type MyType
        for (const key in alpha) {
            const x = this.beta[key as keyof MyType]   // string | number
            const y = alpha[key as keyof typeof alpha] // number | number

            this.beta[key as keyof MyType] = alpha[key as keyof typeof alpha] ?? ''; // expected error
        }
    }
}

如您所见,xandy可以是stringnumber

declare var x: string | number;
x = 42;
x = 'str'

由于 TS 是关于静态类型检查的,因此无法判断是否与this.beta[key]具有相同的类型alpha[keys],它们都是string | number

你得到 Type 'string | number' is not assignable to type 'never'

这是因为对象的键类型是逆变的。并且逆变位置中相同类型变量的候选导致推断交叉类型。因此string & number给出never.

我的建议 - 不要改变打字稿中的值。

您可以在我的博客中找到更多解释和示例

如何解决?

interface MyType {
    a: string;
    b: number;
}

class SomeClass {
    beta: MyType = { a: 'Lorem', b: 3 };

    myFunction(alpha: MyType) {
        const result = (Object.keys(alpha) as Array<keyof MyType>).reduce<MyType>((acc, elem) => ({
            ...acc,
            [elem]: alpha[elem]
        }), this.beta)

        this.beta = result
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章