I've got object with attributes in it. Each attribute has list of properties and it's value type depends on key value. I'm trying to make generic type for converting interface of attribute types to my structure
Here is example of my current code. I cannot set type for attributes.
interface IAttribute<Key, Value> {
key: Key;
value: Value;
approved?: boolean;
published?: boolean;
fromPrototype?: boolean;
}
interface IObject<T> {
id: string;
attributes?: Array<IAttribute<K, T[K]>>; // K extends keyof T. How can I fix it?
}
interface ICustomAttributes {
attr1: boolean;
attr2: number;
}
type ICustom = IObject<ICustomAttributes>;
const o: ICustom = {
id: "1",
attributes: [
{
key: "attr1",
value: true,
},
{
key: "attr2",
value: 123,
},
],
}
Final result must looks like
type ICustomAttributes = IAttribute<"attr1", boolean> | IAttribute<"attr2", number>;
interface ICustom {
id: string;
attributes?: ICustomAttributes[]
}
keyis attribute name,valueis attribute value.valuetype depends onkey. It can be anyattr1to be added to the object multiple times?