मुझे टाइपस्क्रिप्ट के टाइप गार्ड और सशर्त प्रकारों के संयोजन में कुछ समस्याएं आ रही हैं। विचार करना:
export interface IThisThing {
someProp: number;
}
export function isIThisThing(type: any): type is IThisThing {
return !!type.someProp;
}
export interface IThatThing {
someOtherProp: string;
}
export function isIThatThing(type: any): type is IThatThing {
return !!type.someOtherProp;
}
function doAThing<T extends IThisThing | IThatThing>(
data: T
): T extends IThisThing ? IThisThing : IThatThing {
if (isIThisThing(data)) {
return data; // Type 'T & IThisThing' is not assignable to type 'T extends IThisThing ? IThisThing : IThatThing'.
};
return data; // Type 'T' is not assignable to type 'T extends IThisThing ? IThisThing : IThatThing'.
// Type 'IThisThing | IThatThing' is not assignable to type 'T extends IThisThing ? IThisThing : IThatThing'.
// Type 'IThisThing' is not assignable to type 'T extends IThisThing ? IThisThing : IThatThing'.
}
मुझे उम्मीद है कि doAThing
फ़ंक्शन IThisThing
या IThatThing
स्वीकार करेगा और उसी प्रकार को वापस करेगा जैसा इसे प्राप्त होता है। काश संकलक संदेशों की पंक्ति के साथ चोक करता है:
Type 'T & IThisThing' is not assignable to type 'T extends IThisThing ? IThisThing : IThatThing'.
क्या कोई मुझे सीधा कर सकता है? मुझे लगता है कि मैं करीब हूं लेकिन इसे ठीक से नहीं समझ पा रहा हूं। मैं इस ब्लॉग पोस्ट में पहला उदाहरण (जो काफी समान लगता है) का उपयोग कर रहा हूं: http://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/
2 जवाब
टाइपस्क्रिप्ट आपको सशर्त प्रकार के लिए कुछ भी असाइन नहीं करने देगा जिसमें अभी भी फ्री टाइप पैरामीटर है, यह अभी समर्थित नहीं है। आपका सबसे अच्छा दांव जेनेरिक और सशर्त प्रकार के साथ एक हस्ताक्षर और एक सरल कार्यान्वयन हस्ताक्षर है जो दो संभावनाओं का एक संघ देता है
export interface IThisThing {
someProp: number;
}
export function isIThisThing(type: any): type is IThisThing {
return !!type.someProp;
}
export interface IThatThing {
someOtherProp: string;
}
export function isIThatThing(type: any): type is IThatThing {
return !!type.someOtherProp;
}
function doAThing<T extends IThisThing | IThatThing>(
data: T
): T extends IThisThing ? IThisThing : IThatThing
function doAThing(
data: IThisThing | IThatThing
): IThisThing | IThatThing {
if (isIThisThing(data)) {
return data;
};
return data;
}
बस T
लौटाएं:
function doAThing<T extends IThisThing | IThatThing>(
data: T
): T {
if (isIThisThing(data)) {
return data
} else {
return data;
}
}
संबंधित सवाल
नए सवाल
typescript
टाइपस्क्रिप्ट जावास्क्रिप्ट का एक टाइप किया हुआ सुपरसेट है जो सादे जावास्क्रिप्ट को संकलित करता है। यह जावास्क्रिप्ट में वैकल्पिक प्रकार, कक्षाएं, इंटरफेस और मॉड्यूल जोड़ता है। यह टैग टाइपस्क्रिप्ट के लिए विशिष्ट प्रश्नों के लिए है। इसका उपयोग सामान्य जावास्क्रिप्ट प्रश्नों के लिए नहीं किया जाता है।