首页 文章

通用无状态组件的类型是什么?或者在typescript中扩展泛型函数接口以进一步通用?

提问于
浏览
2

ProblemStateless Functional Component 的接口为

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

我的组件的prop类型也是通用的:

interface Prop<V>{
    num: V;
}

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

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

character 27 给出错误 Cannot find name 'T'

这是:Typescript Playground of modified example

MyFindings

1:Typescript 2.9.1支持有状态通用组件: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类型为 anyTypescript React stateless function with generic parameter/return types,这是我不想要的 . 我想为我的道具提供合适的类型

2 回答

  • 0

    你有这个:

    interface Prop<V> {
        num: V;
    }
    

    并且您的组件定义如下:

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

    由于您在组件中实现了 V ,因此不需要为接口中的 V 提供具体类型 .

    看起来像这样:

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

    请注意我使用 object ,你有 T . 这只是一个例子 .

  • 0

    你不能使用这样的泛型:

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

    TypeScript规范说明:

    <T>(...)=> 形式的构造
    可以解析为箭头函数表达式,其类型参数或类型断言应用于没有类型参数的箭头函数 .

    source; Microsoft/TypeScript spec.md

    您的声明与TypeScript规范中定义的模式不匹配,因此它不起作用 .

    但是,您可以不使用SFC接口,只需自己声明 .

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

相关问题