Skip to content

Incorrect types for native errors subtypes #29943

@ethanresnick

Description

@ethanresnick

TypeScript Version: master (3.4.0)

Search Terms: ErrorConstructor

Code

// In Node, ErrorConstructor is augmented with extra properties. Excerpted below.
interface ErrorConstructor {
  captureStackTrace(targetObject: Object, constructorOpt?: Function): void;
}

function myFunction(x: ErrorConstructor) { return true; }
myFunction(Error); // OK

// Error: Property 'captureStackTrace' is missing in type 'RangeErrorConstructor' 
// but required in type 'ErrorConstructor'.
myFunction(RangeError); 

Actual behavior:
Errors, as indicated in the comment.

Expected behavior:

I would expect calling myFunction(RangeError) to work.

According to the spec, the constructor functions for the native errors (RangeError, SyntaxError, etc) have the base Error constructor as their [[Prototype]]. Therefore, I would expect that any augmentations to the base ErrorConstructor type would be visible on the interfaces for the other native error constructors. My first instinct was that this would be accomplished by setting up those child interfaces in lib.es5.d.ts to extend ErrorConstructor, i.e.:

// Proposed lib.es5.d.ts
interface RangeErrorConstructor extends ErrorConstructor { /* ... */ } 
interface SyntaxErrorConstructor extends ErrorConstructor { /* ... */ } 
// etc.

Today, the other error constructor interfaces don't extend ErrorConstructor, so the type system doesn't know that RangeErrorConstructor also has a captureStackTrace function.

However, when I tried to edit lib.es5.d.ts to set up the extends clause, I ran into this error, from the Node typings:

error TS2510: Base constructors must all have the same return type.

1861     export class Recoverable extends SyntaxError {
                                          ~~~~~~~~~~~

I'm not sure what the right way to fix this is, but I do think the behavior in my first code snippet is a bug, and I would hope there's some way to address it (that also still allows the various native error constructors to themselves be subclassable).

Playground Link:
Here

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions