我想为 React props 扩展一个接口。但我收到 TS 错误错误:(19, 35) TS2304: 找不到名称 'T'。
1)为什么会出错?<T>是泛型。不能在使用前声明。
2) 为什么 TS 在我的代码中抛出错误,但没有在此处抛出绝对类型的 React 类型定义。泛型类型<T>和许多其他类型在其代码中随处可见。他们为什么不扔?
3)如何以正确的方式扩展它?
这是我的代码。
我从DefineTyped 为 React导入接口 Props:
import React, {Props, PureComponent} from 'react';
// TS throws Error:(20, 27) TS2304: Cannot find name 'T'.
interface IHomeProps extends Props<T> { }
class Home extends PureComponent<IHomeProps> {
render() {
...
}
}
// interface Props definition
interface Props<T> {
children?: ReactNode;
key?: Key;
ref?: …Run Code Online (Sandbox Code Playgroud) 使用Typescript,在Visual Studio中键入".ts"文件,请考虑以下声明:
export const foo = <T>(myObject: T) => myObject.toString();
Run Code Online (Sandbox Code Playgroud)
这很好用,类型检查很好,一切都很棒.
现在将完全相同的代码放入用于JSX和React的".tsx"文件中.
Intellisense非常沮丧和抱怨,因为它试图将<T>变成React JSX元素.但我的目的是让编译器将其视为通用类型指示符.
编译器抱怨:
[gulp-typescript] 17008 JSX元素'T'没有对应的结束标记.
我已经尝试了许多语法解决方法来尝试让IDE和编译器让我逃脱JSX并强制编译器将<T>理解为通用,就像JSX未使用时一样.但我找不到这种魔法酱.
谁比我更聪明谁能想到这一点?