microsoft / microsoft/TypeScript

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

Open
#13,819 9 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue provides an inline TypeScript reproduction but names no source files or tests. Start by reproducing the derived-constructor case and tracing the compiler's handling of constructor return types; done means the compiler reports when an implicit child-constructor return value cannot satisfy the child class type.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.