microsoft / microsoft/TypeScript

Compiler should complain about implicit return value of child class constructor, if it does not satisfy child class type

未关闭
#13,819 9 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Awaiting More Feedback Suggestion
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

TypeScript Version:  2.1.5

Since TypeScript 2.1 (due to #7574) the return value of a constructor call is the return value of the super constructor. So that

class Child extends Base {}

is compiled to

function Child() {
     return _super !== null && _super.apply(this, arguments) || this;
}

Actual behavior:
The actual problem is, that the implementation of Child(see example below) will be compiled without errors, despite of the fact that the instance (child) does not satisfy its type Child, because someMethod does not exist on child.

class Base {
    hello = 'base';
    constructor() {
        return {
            hello: 'world'
        };
    }
}

class Child extends Base {  // <-- compiler does not complain
    someMethod() {}
}

const child = new Child();
child.someMethod();  // <-- compiler does NOT complain, despite of "someMethod" does not exist on {hello: 'world'}

Expected behavior:
The compiler should complain about the implicit return value of the child class constructor, if this value is not a type of the child class. So that either an explicitly defined return value for the child class constructor should be forced like...

class Child extends Base { 

   constructor() {
     super();
     return { 
       someMethod() {},
       /* ... inherited members */
     }
   }
   someMethod() {}
}

or the return value has to be extended (const base = super()) to fulfill the type Child or all members of the child class have to be optional.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

该 issue 提供了一个 TypeScript 内联复现,但没有指定源文件或测试。首先复现派生构造函数的情况,并跟踪编译器对构造函数返回类型的处理;完成标准是,当隐式的子构造函数返回值无法满足子类类型时,编译器会报告错误。

由索引模型根据 Issue 内容生成。

评估

技术栈
typescript
领域
compilers
Issue 类型
缺陷
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
30/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。