Typescript: Suggestion: stricter type for promise rejection value/reason

Created on 26 Jul 2017  路  4Comments  路  Source: microsoft/TypeScript

TypeScript Version: 2.4.1

Code

promise.catch(error => {
  error.foo.bar // no error. `error` type is `any`
})

In this example, there is no type checking on property lookups on error because error has type any.

I understand it is not possible to know the true type of a the rejected promise value/reason (see https://github.com/Microsoft/TypeScript/issues/5413). However, I would question whether we could replace any with the empty object type {}.

This would mean the above example would throw a type error, which is desirable because it is safer. The user may widen choose the type of error using user-defined type guards.

Has this been considered at all? I am also curious if the same idea could be applied to other uses of any in libs.

Declined

Most helpful comment

This has definitely been brought up before (eg here and here in more detail here).

As you say, any in .d.ts files makes consuming code less type safe by silently disabling type-checking in parts of your code, such as in your example with promise.catch.

A suggested solution that I quite like has been made in #10715.

However, updating all the any annotations in lib files to {} or unknown would be a breaking change.

All 4 comments

This has definitely been brought up before (eg here and here in more detail here).

As you say, any in .d.ts files makes consuming code less type safe by silently disabling type-checking in parts of your code, such as in your example with promise.catch.

A suggested solution that I quite like has been made in #10715.

However, updating all the any annotations in lib files to {} or unknown would be a breaking change.

@yortus I think TypeScript should just set the reason parameter to Error rather than any because rejecting with anything but an error likely doesn't give you a stack trace.

I do not think we will be open to taking such a breaking change in the standard library. a local change to the Promise definition should achieve the desired outcome.

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

blendsdk picture blendsdk  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

bgrieder picture bgrieder  路  3Comments

dlaberge picture dlaberge  路  3Comments