【问题标题】:Error TS2415 in simple Typescript/React class简单 Typescript/React 类中的错误 TS2415
【发布时间】:2018-04-06 17:16:18
【问题描述】:

TS2415:“MyComponent”类错误地扩展了基类

我创建了以下代码sn-p:

import * as React from "react";

export interface IMyProps {
}

export interface IMyState {
}

export class MyComponent extends React.Component<IMyProps, IMyState> {
    constructor(props: IMyProps) { 
        super(props);
    }

    render() {

    }
}

但是 TypeScript 编译器给了我以下错误:

(9,14):错误 TS2415:“MyComponent”类错误地扩展了基础 类“组件”。属性“渲染”的类型 不兼容。 类型 '() => void' 不可分配给类型 '() => false |元素'。 类型 'void' 不可分配给类型 'false |元素'。

这里有什么问题?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    我必须在 render 方法中添加一个 return 语句才能编译:

    import * as React from "react";
    
    export interface IMyProps {
    }
    
    export interface IMyState {
    }
    
    export class MyComponent extends React.Component<IMyProps, IMyState> {
        constructor(props: IMyProps) { 
            super(props);
        }
    
        render() {
            return <div/> // I had to return a valid return type here.
        }
    }
    

    我认为这是因为在返回语句被解释之前,返回类型是未知的。 在那之前,render() 方法被解释为返回 'void'。

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 2022-11-25
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多