मुझे इसमें attributes
के साथ ऑब्जेक्ट मिला है। प्रत्येक विशेषता में गुणों की सूची होती है और इसका मान प्रकार कुंजी मान पर निर्भर करता है। मैं अपनी संरचना में विशेषता प्रकारों के इंटरफ़ेस को परिवर्तित करने के लिए सामान्य प्रकार बनाने की कोशिश कर रहा हूँ
मेरे वर्तमान कोड का उदाहरण यहां दिया गया है। मैं 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,
},
],
}
अंतिम परिणाम इस तरह दिखना चाहिए
type ICustomAttributes = IAttribute<"attr1", boolean> | IAttribute<"attr2", number>;
interface ICustom {
id: string;
attributes?: ICustomAttributes[]
}
1 उत्तर
आप मैप किए गए प्रकार का उपयोग करके प्रकार के गुणों को IAttribute के संघ में परिवर्तित कर सकते हैं:
interface IAttribute<Key, Value> {
key: Key;
value: Value;
approved?: boolean;
published?: boolean;
fromPrototype?: boolean;
}
interface IObject<T> {
id: string;
attributes?: Array<{ [P in keyof T]: IAttribute<P, T[P]> }[keyof T]>; // 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,
},
],
}
हालांकि यह सुनिश्चित नहीं करता है कि प्रत्येक सदस्य कम से कम एक बार उपस्थित हो और कोई डुप्लिकेट न हो। आपके उपयोग के मामले के आधार पर यह समस्या हो भी सकती है और नहीं भी। यदि आपको यह सुनिश्चित करने की आवश्यकता है कि प्रत्येक सदस्य ठीक उसी समय मौजूद है जब आप किसी सरणी के बजाय किसी ऑब्जेक्ट का उपयोग करना बेहतर समझते हैं (आप टुपल्स के साथ एक समान प्रभाव प्राप्त कर सकते हैं लेकिन ऑब्जेक्ट प्रकार को सभी संभावित टुपल्स के संघ में परिवर्तित करने के लिए रिकर्सिव प्रकार का उपयोग करने की आवश्यकता होगी उपनाम जो अनुशंसित नहीं हैं)
interface IObject<T> {
id: string;
attributes?: { [P in keyof T]: IAttribute<P, T[P]> }
}
interface ICustomAttributes {
attr1: boolean;
attr2: number;
}
type ICustom = IObject<ICustomAttributes>;
const o: ICustom = {
id: "1",
attributes: {
"attr1": {
key: "attr1",
value: true,
},
"attr2": {
key: "attr2",
value: 123,
},
}
}
संबंधित सवाल
नए सवाल
typescript
टाइपस्क्रिप्ट जावास्क्रिप्ट का एक टाइप किया हुआ सुपरसेट है जो सादे जावास्क्रिप्ट को संकलित करता है। यह जावास्क्रिप्ट में वैकल्पिक प्रकार, कक्षाएं, इंटरफेस और मॉड्यूल जोड़ता है। यह टैग टाइपस्क्रिप्ट के लिए विशिष्ट प्रश्नों के लिए है। इसका उपयोग सामान्य जावास्क्रिप्ट प्रश्नों के लिए नहीं किया जाता है।