Home > OS >  In TypeScript, how to invalidate truth assertion after asynchronous operation?
In TypeScript, how to invalidate truth assertion after asynchronous operation?

Time:12-21

The code is as follows:

function delay(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

const obj: { a?: () => any } = {
  a: () => {},
};

async function test() {
    if (obj.a) { 
        await delay(1000);
        obj.a() // want an obj.a may be undefined error
        delete obj.a
    }
}

test()
test() // TypeError: obj.a is not a function

I remember that TypeScript supported this feature a long time ago. I'm not sure whether it is still available now?

CodePudding user response:

Since you are already checking if (obj.a), TypeScript will not complain that obj.a can be undefined.

What are you trying to achieve by the way? Usually the usage of delete is not really recommended, there should be a better way.

CodePudding user response:

This is a TOCTOU bug:

TS Playground

async function test() {
  if (obj.a) { 
    await delay(1000);
    obj.a() // want an obj.a may be undefined error
    delete obj.a
  }
}

A better way to write it is not to check at all, but to only invoke obj.a if it exists using the Optional chaining operator (?.):

TS Playground

async function test() {
  await delay(1000);
  obj.a?.() // possibly undefined, but only invoke if exists
  delete obj.a
}
  • Related