我有两个使用"props“的数据结构,其中一种类型的prop更简单,另一种类型的prop更复杂。简单的道具类型用于“元素”,复杂的道具类型用于“组件”。
这是一个简单的数据结构:
export interface IPageElementProps {
maxContainerWidth: number
}
export interface ITextElementProps {
text: string
styleRanges: ICanvasTextElementStyleRange[]
}
然后复制其中的每一个,以允许组件的属性使用更复杂的数据结构:
export interface IPageComponentProps {
maxContainerWidth: IComponentProp<number>
}
export interface ITextComponentProps {
text: IComponentProp<string>
styleRanges: IComponentProp<ICanvasTextElementStyleRange[]>
}
/**
* A component property defines whether a property is injectable (dynamic)
* or whether it is hardcoded within the component (non-dynamic or static).
*/
export interface IComponentProp<T> {
dynamic: boolean
value?: T
defaultValue?: T
}
我倾向于使用泛型类型参数,而不必重新定义每种类型的元素/组件(一种用于简单数据结构,另一种用于复杂数据结构)。大致是这样的:
export interface IPageProps<T = undefined> {
maxContainerWidth: T<number>
}
然后,我将简单类型用作简单props: IPageProps
,将其用于复杂类型作为props: IPageProps<IComponentProp>
。
这有意义吗? Typescript中有这样的功能吗?
发布于 2019-03-06 17:44:08
您可以创建一个新的泛型类型,它将为您完成此操作。新类型将遍历给定类型的所有属性,并将每个属性“转换”为IComponentProp
如下所示:
export interface IPageElementProps {
maxContainerWidth: number;
}
export interface ITextElementProps {
text: string;
styleRanges: ICanvasTextElementStyleRange[];
}
export interface IComponentProp<T> {
dynamic: boolean;
value?: T;
defaultValue?: T;
}
// This is the magic type
type PageProps<T> = { [P in keyof T]: IComponentProp<T[P]> };
// There new types will do the job
type IPageComponentProps = PageProps<IPageElementProps>;
type ITextComponentProps = PageProps<ITextElementProps>;
https://stackoverflow.com/questions/55029008
复制相似问题