如何输入记录/映射扩展公共属性接口的React组件

时间:2019-03-20 00:52:39

标签: reactjs typescript

我正在构建一个库,该库将接受带有特定基础道具集的组件的映射:

import {ComponentType} from 'react';

interface BaseProps {
  a: string;
  b: number;
  [key: string]: any;
}

interface Registry = {
  [key: string]: ComponentType<BaseProps>
}

然后用户可以执行以下操作:

import React from 'react';

interface UserProps extends BaseProps {
  c: number;
}

class UserComponent extends React.Component<UserProps>{
  //omitted for brevity
}

const registry: Registry = {
  "myComponent": UserComponent
}

这将引发如下类型错误:

Type 'Readonly<BaseProps>' is missing the following
properties from type 'Readonly<UserProps>': c

尽管BasePropsUserProps不等效(尽管我确实在BaseProps上具有通用索引...)确实有意义,但我基本上想要这样的东西:

interface Registry = {
  [key: string]: ComponentType<anything that extends BaseProps>
}

有没有办法做到这一点?与Java(http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#What%20is%20a%20wildcard%20instantiation)中的通配符类型运算符相似或在功能上相似?

0 个答案:

没有答案