TypeScript - tsx 文件中无法识别类型参数?

nag*_*lzs 4 generics jsx typescript

我有一个名为“test.ts”的示例文件,其中包含以下代码:

const test = <T>(a: string) => { return a; } ;
Run Code Online (Sandbox Code Playgroud)

有用!如果我将文件重命名为“test.tsx”,则 Visual Studio Code 将 T 参数标记为红色,并给出以下错误:

[ts] Cannot find name 'T'.

[ts] JSX element 'T' has no corresponding close tag.
Run Code Online (Sandbox Code Playgroud)

我必须使用 .tsx 扩展名,因为实际代码需要返回 JSX 元素。我还必须使用类型参数。但我怎样才能两者兼得呢?

Tit*_*mir 6

Tsx 和通用箭头函数不能很好地混合。最简单的解决方案是使用常规函数,因为this无论如何您都不会从声明上下文中捕获:

const withLazyStatus = function<T>(WrappedComponent: React.ComponentType<ILazyState<T>>) {
    return class WithLazyStatus extends React.Component<ILazyState<T>> {
        // Enhance component name for debugging and React-Dev-Tools
        static displayName = `withLazyStatus(${WrappedComponent.name})`;

        render() {
            let props = this.props;
            if (props.fetching) {
                return loading;
            } else if (props.error) {
                return error(props.error);
            } else {
                return <WrappedComponent {...this.props} />;
            }
        }
    };
};
Run Code Online (Sandbox Code Playgroud)

或者另一个选项是添加类型约束:

 const withLazyStatus = <T extends object>(WrappedComponent: React.ComponentType<ILazyState<T>>) {
        return  ...
  };
Run Code Online (Sandbox Code Playgroud)

该约束将消除通用与标签结构的歧义

  • &lt;T extends object&gt; 是天才 (2认同)