gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:19 26 4
gpt4 key购买 nike

我有一个名为“test.ts”的示例文件,代码如下:

const test = <T>(a: string) => { return a; } ;

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

[ts] Cannot find name 'T'.

[ts] JSX element 'T' has no corresponding close tag.

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

最佳答案

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

或者另一种选择是添加类型约束:

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

约束将消除通用与标记构造的歧义

关于TypeScript - tsx 文件中无法识别类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48523370/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com