Attempting to explain a simple method in TypeScript.
This method should allow modification of data for any object type within the data
attribute.
In simpler terms, we can modify, add, or remove data based on the specified data type, and TypeScript facilitates this by establishing clear associations with each type. For instance, if the value to be modified is a number, the system only allows entry of numerical values.
(I hope that's clear).
Here's an easy-to-understand 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("backgroundColor", "#000"); // Needs to be a string
o.setBackgroundProperty("backgroundColor", 0); // Error received
o.setBackgroundProperty("paddingBottom", 10); // Should be a number
o.setBackgroundProperty("paddingBottom", "10"); // Error encountered
At present, my code looks like this:
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;
}
}
However, I encounter an error on this line:
this.data.background[key] = value;
.
The error message states:
Type 'K' cannot be used to index type 'BackgroundProperties'.
I've searched for solutions online but have been unable to identify the root cause.
Here's a replicated example on TypeScript Playground.