Skip to content

Syntax for passing generic into function type annotation #27124

@OliverJAsh

Description

@OliverJAsh

I have a function type StatelessFunctionComponent (aka SFC) that I use as an annotation like so:

import * as React from 'react';
import { SFC } from 'react';

// Imported types look like:
// import { ReactNode, ReactElement } from 'react';
// type SFC<P> = (props: P & { children?: ReactNode }, context?: any) => ReactElement<any> | null

type Props = {};
const MyComponent: SFC<Props> = props => <div>Hello, World!</div>

I would like to pass a generic into this function type via the annotation. However, that does not appear to be possible.

Pseudo-code:

import * as React from 'react';

type Props<T> = { t: T };
// How can we make this function receive a generic that is passed into
// the function type annotation?
const MyComponent: <T> SFC<Props<T>> = props =>
  <div>Hello, World!</div>

Is there any existing or suggested syntax that could support this?

One workaround is to avoid the type annotation altogether, and instead just write the function signature out manually:

import * as React from 'react';
import { ReactElement } from 'react';

type Props<T> = { t: T };
// Since we have no way of passing the generic into the function type annotation,
// we have to write out the full function type
const MyComponent = <T>(props: Props<T>): ReactElement<any> | null =>
  <div>Hello, World!</div>

Another workaround is to use a createSubType helper:

import * as React from 'react';
import { SFC } from 'react';

const createSubType = <T extends any>() => <SubType extends T>(
    subType: SubType,
) => subType;

const createGenericSFC = createSubType<SFC<any>>();

type Props<T> = { t: T };
const MyComponent = createGenericSFC(<T extends any>(props: Props<T>) => (
    <div>Hello, World!</div>
));

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions