Jurosh
Jurosh

Reputation: 7767

Typescript React stateless function with generic parameter/return types

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

Example component:

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 />;
}

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

Desired usage:

// 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} />

Edit: Should do same job as function does:

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

SFC Type has definition:

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

Upvotes: 6

Views: 4589

Answers (1)

Jokester
Jokester

Reputation: 5617

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} />;

Upvotes: 5

Related Questions