Typescript使用通用参数/返回类型来响应无状态函数 [英] Typescript React stateless function with generic parameter/return types

查看:55
本文介绍了Typescript使用通用参数/返回类型来响应无状态函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何基于参数或外部配置在React无状态组件中定义通用类型?

How to define generic type in React stateless components based on parameter, or outside configuration?

示例组件:

interface IProps<V> {
  value: V;
  doSomething: (val: V) => void;
}

const Comp: React.SFC<IProps<number>> = <T extends number>({
   value: T,
   doSomething
  }) => {
 return <div />;
}

上面的示例将起作用,但仅将数字作为值.

Above example will work, but only with numbers as values.

可以进行升级以达到以下目的:

Is possible to do upgrade to achieve something like:

const Comp: React.SFC<IProps<??>> = <?? extends string | number>({
   value, /* of type ?? */
   doSomething
  }) => {
 return <div />;
}

这样,当我们使用component时,我们可以决定我们想要的数字还是字符串.

So that we can decide whatever we want numbers, or strings when using component.

所需用法:

// This should setup generic type to string
<Comp value="string" ... />

// Or number
<Comp value={123} ... />

// Should be compilation error as we cannot use * on 'text' * 5
<Comp value="text" doSomething={val => val * 5} />

应执行与function相同的工作:

 function Comp <T>({value, doSomething}: IProps<T>) { ... }

SFC类型具有定义:

SFC Type has definition:

interface SFC<P> {
  (props: P & { children?: ReactNode }, context?: any): ReactElement<any>;
  ...
}

推荐答案

我能够在TS 2.3中做到这一点.关键是要对该组件的内部"和外部"使用两种类型.

I was able to do this in TS 2.3. The point is to use 2 types for "inside" and "outside" of that component.

interface IProps<V> {
    value: V;
    doSomething(val: V): void;
}

// type "inside" component
function _Comp<T>(props: IProps<T>) {
    return <div />;
}

// type for "outside" of component
interface GenericsSFC extends React.SFC<any> {
    <T>(props: IProps<T> & { children?: React.ReactNode }, context?: any): JSX.Element;
}

const Comp = _Comp as GenericsSFC;

// dont type check: v is of type "hey"
<Comp value={"hey"} doSomething={v => v - 1} />;

这篇关于Typescript使用通用参数/返回类型来响应无状态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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