javascript – 通用无状态组件的类型是什么?或者在typescript中扩展泛型函数接口以进一步通用?

问题:无状态功能组件的接口给出为

interface SFC<P = {}> {
    (props: P & { children?: ReactNode }, context?: any): ReactElement<any> | null;
    propTypes?: ValidationMap<P>;
}

我的组件的prop类型也是通用的:

interface Prop<V>{
    num: V;
}

如何正确定义我的组件?如:

const myCom: <T>SFC<Prop<T>> = <T>(props: Prop<T>)=> <div>test</div>

在字符27处出现错误,找不到名称’T’

这是:Typescript Playground of modified example

MyFindings:

1:Typescript 2.9.1支持有状态通用组件:http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#generic-type-arguments-in-jsx-elements

class myCom<T> extends React.Component<Prop<T>, any> {
   render() {
      return <div>test</div>;
   }
}

2:扩展SFC以创建一个新接口,如下面的答案中所述,将使组件的prop类型为any:
Typescript React stateless function with generic parameter/return types我不想要.我想为我的道具提供合适的类型

解决方法:

你不能使用这样的泛型:

const myCom: <T>SFC<Prop<T>> = <T>(props: Prop<T>)=> <div>test</div>

TypeScript规范指出:

A construct of the form

06001

Could be parsed as an arrow function expression with a type parameter or a type assertion applied to an arrow function with no type parameter.

source; Microsoft/TypeScript spec.md

您的声明与TypeScript规范中定义的模式不匹配,因此它不起作用.

但是,您可以不使用SFC接口,只需自己声明.

interface Prop<V> {
    num: V;
}

// normal function
function Abc<T extends string | number>(props: Prop<T>): React.ReactElement<Prop<T>> {
    return <div />;
}

// const lambda function
const Abc: <T extends string | number>(p: Prop<T>) => React.ReactElement<Prop<T>> = (props) => {
   return <div />
};

export default function App() {
    return (
        <React.Fragment>
            <Abc<number> num={1} />
            <Abc<string> num="abc" />
            <Abc<string> num={1} /> // string expected but was number
        </React.Fragment>
    );
}

相关文章

我最大的一个关于TypeScript的问题是,它将原型的所有方法(无...
我对React很新,我正在尝试理解子组件之间相互通信的简洁方法...
我有一个非常简单的表单,我将用户电子邮件存储在组件的状态,...
我发现接口非常有用,但由于内存问题我需要开始优化我的应用程...
我得到了一个json响应并将其存储在mongodb中,但是我不需要的...
我试图使用loadsh从以下数组中获取唯一类别,[{"listing...