用一个方法修改类中的一个对象。

huangapple go评论69阅读模式
英文:

Modify an object in a class with a method

问题

Here is the translated content:

我正在尝试用TypeScript描述一个相当简单的方法。

该方法必须允许修改data属性的任何对象类型的数据。
换句话说,我们可以修改、添加或删除数据,而TypeScript允许我们通过正确关联每个类型来动态执行此操作。如果要修改的值是一个数字,那么只会留下可以填充的数字。
(我不确定是否清楚)。

这里是一个简单的示例:

interface BackgroundProperties {
    backgroundColor: string;
    paddingTop: number;
    paddingBottom: number;
    paddingLeft: number;
    paddingRight: number;
    hasShadow: boolean;
    shadowBlur: number;
    shadowColor: string;
    shadowOffsetX: number;
    shadowOffsetY: number;
}

const o = new Obj();
o.setBackgroundProperty("backgroundColor", "#000"); // 需要是字符串
o.setBackgroundProperty("backgroundColor", 0); // 报错
o.setBackgroundProperty("paddingBottom", 10); // 需要是数字
o.setBackgroundProperty("paddingBottom", "10"); // 报错

目前,我有以下代码:

interface BackgroundProperties {
    backgroundColor: string;
    paddingTop: number;
    paddingBottom: number;
    paddingLeft: number;
    paddingRight: number;
    hasShadow: boolean;
    shadowBlur: number;
    shadowColor: string;
    shadowOffsetX: number;
    shadowOffsetY: number;
}

class Obj {
  data: { background: BackgroundProperties };

  constructor() {
    this.data = {
     background: {
          backgroundColor: "#ABB8C3",

          hasShadow: true,
          shadowColor: "rgba(0,0,0,0.55)",
          shadowBlur: 68,
          shadowOffsetY: 12,
          shadowOffsetX: 0,

          paddingBottom: 56,
          paddingTop: 56,
          paddingLeft: 56,
          paddingRight: 56
      }
    }
  }

  public setBackgroundProperty<O extends BackgroundProperties, K extends keyof O>(key: K, value: O[K]) {
        if (String(key).endsWith('Color') && typeof value === 'string' ? value : '')
            throw new Error(`The ${key.toString()} background color value is not a hexadecimal color!`);


        this.data.background[key] = value;
        return this;
  }
}

但是,我在这一行上遇到了错误:this.data.background[key] = value;
错误信息是:

Type 'K' cannot be used to index type 'BackgroundProperties'.

我已经在互联网上寻找解决方案,但找不到问题出在哪里。

TypeScript Playground上重现的示例。

英文:

I'm trying to describe a fairly simple method in TypeScript.

The method must allow any object type of the data attribute to modify its data.
In other words, we can modify, add or remove data in the data type, and dynamically, TypeScript allows us to do this by associating each type well. If the value to be modified is a number, then it leaves only numbers to be filled in.
(I'm not sure that's clear).

Here is a simple example:

interface BackgroundProperties {
    backgroundColor: string;
    paddingTop: number;
    paddingBottom: number;
    paddingLeft: number;
    paddingRight: number;
    hasShadow: boolean;
    shadowBlur: number;
    shadowColor: string;
    shadowOffsetX: number;
    shadowOffsetY: number;
}

const o = new Obj();
o.setBackgroundProperty(&quot;backgroundColor&quot;, &quot;#000&quot;); // Needs to be a string
o.setBackgroundProperty(&quot;backgroundColor&quot;, 0); // Got an Error
o.setBackgroundProperty(&quot;paddingBottom&quot;, 10); // Needs to be a number
o.setBackgroundProperty(&quot;paddingBottom&quot;, &quot;10&quot;); // Got and error

For the moment, I've the following code:

interface BackgroundProperties {
    backgroundColor: string;
    paddingTop: number;
    paddingBottom: number;
    paddingLeft: number;
    paddingRight: number;
    hasShadow: boolean;
    shadowBlur: number;
    shadowColor: string;
    shadowOffsetX: number;
    shadowOffsetY: number;
}

class Obj {
  data: { background: BackgroundProperties };

  constructor() {
    this.data = {
     background: {
          backgroundColor: &quot;#ABB8C3&quot;,

          hasShadow: true,
          shadowColor: &quot;rgba(0,0,0,0.55)&quot;,
          shadowBlur: 68,
          shadowOffsetY: 12,
          shadowOffsetX: 0,

          paddingBottom: 56,
          paddingTop: 56,
          paddingLeft: 56,
          paddingRight: 56
      }
    }
  }

  public setBackgroundProperty&lt;O extends BackgroundProperties, K extends keyof O&gt;(key: K, value: O[K]) {
        if (String(key).endsWith(&#39;Color&#39;) &amp;&amp; typeof value === &#39;string&#39; ? value : &#39;&#39;)
            throw new Error(`The ${key.toString()} background color value is not a hexadecimal color!`);


        this.data.background[key] = value;
        return this;
  }
}

But, I have an error on this line: this.data.background[key] = value;.
The error is:

Type &#39;K&#39; cannot be used to index type &#39;BackgroundProperties&#39;.

I've been looking for solutions on the internet, but I can't find where it comes from.

Here is an example reproduced on TypeScript Playground.

答案1

得分: 1

以下是已翻译的内容:

"Since you are declaring that O extends BackgroundProperties, there is no guarantee that K is a valid key of BackgroundProperties itself. It could be a key of the extended type. But data.background is of type BackgroundProperties, and can only accept keys of that type.

To fix the issue, you could change the signature like so:

public setBackgroundProperty<K extends keyof BackgroundProperties>(key: K, value: BackgroundProperties[K]) {"

英文:

Since you are declaring that O extends BackgroundProperties, there is no guarantee that K is a valid key of BackgroundProperties itself. It could be a key of the extended type. But data.background is of type BackgroundProperties, and can only accept keys of that type.

To fix the issue, you could change the signature like so:

public setBackgroundProperty&lt;K extends keyof BackgroundProperties&gt;(key: K, value: BackgroundProperties[K]) {

huangapple
  • 本文由 发表于 2023年4月17日 17:12:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76033495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定