错误:(19, 35) TS2304:找不到名称“T”。为什么我不能在 TS 中扩展接口?

IT技术 reactjs typescript generics
2021-05-27 09:59:39

我想为 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?: LegacyRef<T>;
    }
2个回答

您需要T在您定义的接口上指定一个具体的或声明一个泛型类型参数。

在react定义代码的工作,因为他们定义T<T>接口后的定义T,所以它可以再界面内使用。定义自己的接口时,需要定义自己的类型参数T,然后将if转发到Props这是定义的版本的T样子:

interface IHomeProps<T> extends Props<T> { }
                 //  ^ T is defined   ^ T is used

您可能只想为 提供一个具体类型T

interface IHomeProps extends Props<HTMLDivElement> { }

class Home extends PureComponent<IHomeProps> {
    render() {
        return <div></div>
    }
}

简单的函数示例。只需扩展 ObjectLiteral 类型。

前:

private filterNull(data: Array<any>) {
    return data.filter(x => !!x);
}

后:

private filterNull<T extends ObjectLiteral>(data: Array<T>): Array<T> {
    return data.filter(x => !!x);
}