英文:
What does providing multiple interfaces in generic syntax while extending do?
问题
以下是React中一行我不太理解的代码。我知道partial是什么意思,但还是感到有点困惑。我们本来可以分别扩展它们的。如果我错了,请纠正我。以下是代码行:
export class SearchFilterPanelPositions extends Component<Partial<ISearchFilterPanelBasePropTypes & ISearchFilterPanelPropTypes>, ISearchTypesBaseState> {
...
...
}
SearchFilterPanelPositions 扩展了什么,以及如何扩展的?
英文:
Following is the line in react that I don't understand. I know what partial does but its a little confusing. We could have extended them separately. Correct me if I am wrong. Following is the line of code:
export class SearchFilterPanelPositions extends Component<Partial<ISearchFilterPanelBasePropTypes & ISearchFilterPanelPropTypes>, ISearchTypesBaseState> {
...
...
}
What is the SearchFilterPanelPositions extending and how?
答案1
得分: 1
-
在TS中,
Partial
会使传递给它的类型参数的所有属性变成可选的。假设我们有以下接口:interface ISearchFilterPanelBasePropTypes { prop1: string; } interface ISearchFilterPanelPropTypes { prop2: string; }
将
Partial
应用于上述接口的交集后,我们将得到以下类型的形状:{ prop1?: string; } & { prop2?: string; }
因此,来自两个接口的属性都变成了可选的(可以分配为
undefined
)。 -
Component
是React组件的基础类型,它有两个类型参数,props 和 state。对于props,使用上面的类型。因此,您将得到:export class SearchFilterPanelPositions extends Component<Partial<ISearchFilterPanelBasePropTypes & ISearchFilterPanelPropTypes>, ISearchTypesBaseState> { constructor(props) { super(props); props.prop1 // 可以是string或undefined props.prop2 // 也可以是string或undefined } // ... // ... }
上面的组件可以这样使用:
<SearchFilterPanelPositions /> // 没有提供props <SearchFilterPanelPositions prop1='prop1' /> // 只提供prop1 <SearchFilterPanelPositions prop1='prop1' prop2='prop2' /> // 提供了prop1和prop2
英文:
-
Partial
in TS make all properties of passed type argument optional. Sya we haveinterface ISearchFilterPanelBasePropTypes { prop1: string; } interface ISearchFilterPanelPropTypes { prop2: string; }
After applying
Partial
to intersection of above interfaces we'll have type of shape:{ prop1?: string; } & { prop2?: string; }
So properties from both interfaces become optional (can be assigned
undefined
). -
Component
is React Component base type which has two type arguments, props and state. For props, above type is passed.
As a result, you'll have
export class SearchFilterPanelPositions extends Component<Partial<ISearchFilterPanelBasePropTypes & ISearchFilterPanelPropTypes>, ISearchTypesBaseState> {
constructor(props) {
super(props);
props.prop1 // can be string or undefined
props.prop2 // can also be string or undefined
}
...
...
}
And above component can be used as
<SearchFilterPanelPositions /> // Without props
<SearchFilterPanelPositions prop1='prop1' /> // With only prop1 provided
<SearchFilterPanelPositions prop1='prop1' prop2='prop2' /> // Both prop1 and prop2 provided
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论