通用无状态组件的类型是什么?或者在typescript中扩展泛型函数接口以进一步通用? [英] Type of Generic Stateless Component React? OR Extending generic function interface in typescript to have a further generic?

查看:168
本文介绍了通用无状态组件的类型是什么?或者在typescript中扩展泛型函数接口以进一步通用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题无状态功能组件的界面为

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

我的组件的道具类型也是通用的:

The prop type of my component is also generic as:

interface Prop<V>{
    num: V;
}

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

How to properly define my component? as:

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

错误字符27 找不到名字'T'

这是:打字稿游乐场修改后的示例

MyFindings

1:打字稿2.9 .1支持有状态通用组件: http://www.typescriptlang.org/docs/hand book / release-notes / typescript-2-9.html#generic-type-arguments-in-jsx-elements

1:Typescript 2.9.1 support Stateful Generic Component: 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无状态函数,我不想要。我想为我的道具提供适当的类型

2: Extending SFC to make a new interface as mentioned in following answer would make component's prop type as any: Typescript React stateless function with generic parameter/return types which I don't want. I want to give proper type for my prop

推荐答案

你不能使用这样的泛型:

You can't use generics like this:

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

TypeScript规范声明:

The TypeScript spec states:


表格的构造

A construct of the form

< T > ( ... ) => { ... }

可以解析为带有类型参数或类型断言的箭头函数表达式应用于没有类型参数的箭头函数。

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规范中定义的模式不匹配,因此它不起作用。

Your declaration doesn't match the pattern defined in the TypeScript spec, therefore it wont work.

但是你可以不使用SFC接口而只是自己声明。

You can however don't use the SFC interface and just declare it yourself.

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中扩展泛型函数接口以进一步通用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆