Home > Enterprise >  Is it possible to satisfy the TS compiler without resorting to the non-null assertion?
Is it possible to satisfy the TS compiler without resorting to the non-null assertion?

Time:01-25

I have the following class :

export class Deferred<R> {
  promise: Promise<R>;
  resolve: (value: R|PromiseLike<R>) => void;
  reject: (error?: any) => void;

  constructor() {
    this.promise = new Promise((res, rej) => {
      this.resolve = res;
      this.reject = rej;
    });
  }
}

It is possible to remove the compiler warnings without resorting to the non-null assertion ! nor the marking the properties optional which they aren't because the construstor runs synchronously ?

Playground

CodePudding user response:

You set the properties of the class in the function, that compiler has no means to know upfront if it's gonna be run sync or async, or maybe it won't be run at all. But YOU know the answer given you know how Promises work.

So, I'd say ! is the way to go

export class Deferred<R> {
  promise: Promise<R>;
  resolve!: (value: R|PromiseLike<R>) => void;
  reject!: (error?: any) => void;

  constructor() {
    this.promise = new Promise((res, rej) => {
      this.resolve = res;
      this.reject = rej;
    });
  }
}

Here's a quote

If you intend to definitely initialize a field through means other than the constructor (for example, maybe an external library is filling in part of your class for you), you can use the definite assignment assertion operator, !

Source: https://www.typescriptlang.org/docs/handbook/2/classes.html

  • Related