'Use of typescript generics for extended parametres
My purpose is simple: I want to find a way of using generics for extended parametres, in this example, throwData is the thing I am interested in. Instead of any, I want to use something more informative such as generic. Is there any way I can stuff like that?
titleStylesCondition<
IP extends {
hasOwnProperty: (a: string) => boolean;
throwData?: any;
title?: string;
}
>(itemProps: IP) {
const { palette, isDark } = this.context;
const styles = getStyles(palette, isDark);
const titleStyles = this.get("props.titleStyles", {});
if (
itemProps.hasOwnProperty("Industry") ||
itemProps.throwData.hasOwnProperty("Auto") ||
itemProps.title === "BMW"
) {
return styles.autoStyling;
}
Solution 1:[1]
Sure, just add another generic to hold its type:
titleStylesCondition<
IP extends {
hasOwnProperty: (a: string) => boolean;
throwData?: ThrowData;
title?: string;
},
ThrowData,
>(itemProps: IP) {
Most of the time, TypeScript can infer this ThrowData generic properly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hittingonme |
