Typescript React stateless function with typical parameters / return types

How to determine generic type in React stateless section based on parameter or out of configuration?

Component example:

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

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

      

The above example will work, but only with numbers as values.

An update can be performed to achieve something like:

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

      

So, we can decide that we want numbers or strings to be used when using the component.

Desired use:

// 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: The same job should be done as function

:

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

      

The SFC type has a definition:

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

      

+3


source to share


1 answer


I was able to do this in TS 2.3. The point is to use 2 types for "inside" and "outside" this 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} />;

      

+3


source







All Articles