【发布时间】:2021-06-21 16:59:53
【问题描述】:
我有一张存储各种元素的地图。定义如下:
const map = new Map<string, IComponent<IBase>>();
我想用这个映射来存储IComponent<IBase>、IComponent<INumber>、IComponent<IText>等的实例。
基本接口定义如下:
// base interface
interface IBase {}
// base component type
export type IComponent<T extends IBase> = React.FC<T>;
现在我想添加一个NumberComponent
// derived interface
interface INumber extends IBase {
someNumber: number;
}
// some component
const NumberComponent: IComponent<INumber> = (props) => {
return (
<div>{props.someNumber}</div>
);
}
我使用map.set('number', NumberComponent) 将其存储到地图中,但我得到了
Argument of type 'FC<INumber>' is not assignable to parameter of type 'FC<IBase>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'PropsWithChildren<IBase>' is not assignable to type 'PropsWithChildren<INumber>'.
Property 'someNumber' is missing in type 'PropsWithChildren<IBase>' but required in type 'INumber'.
我知道我可以使用map.set('number', NumberComponent as IComponent<IBase>) 来转换类型。但是,我不想使用as。有没有其他方法可以解决这个问题?
【问题讨论】:
-
我不确定你想用地图实现什么。我想你基本上希望能够调用
map.get('number');并接收一个类型化的数字组件,但是由于只输入了值,TypeScript 不会知道键“数字”后面有 NumberComponent。 -
/play?ts=3.9.7#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wG4AocgeirgCMUBnJOYAOxiSk3SXPc7decAJIAhJiwDeAX2q00uSGyQc4MAJ5g+SAB6RY6rSxEBhJRBUcAPABU4ezmwAmjUROZwAvHFkA+b0RiGAA6ADFTOz8KSho4Zy5gADckZ1YOLh40PgFM4REAOQBXEDouB10nV3dJX3I4BrhGXCRi0q4ALjg2ErKoCjl+DKFs0VtHCqq3cVqpesbOSq7GGCh2AHMB+SaWuEVwS1UYckU2Fbg2vvMDqxguswtb60LergCfAAowHDBGAEpvAE5o04EQYEUoGw4B95iCGtZnMk-FJvhBfiFmiBWq8oDJrFREUk-LC4H8tidLOdxpVrsojvdaYcbCJqTB3tDUb8AV4gSSwRCoTC4Y0EUiUT9GCFFjA8QSkSS-uRBqdziAUGBAsDGgAiHrtKDarqXLiM24AGhJ2ulhrgrNNRwtMjgTD2lJgMQpZ3gCAgEBg9o4XWQ6FCEUCH25vJBKvgAfgPjVYCljhiIP5kLg1jj6kcXm1AAkkAAbIsQOAAdWgRec2rgVGiSqAA
标签: reactjs typescript