Why isn't TypeScript complaining about this?

When compiling with ES2015, there is strange behavior when typing Promise.

In the following code, the first two functions ( str

and strA

) fail, stating that string | number

is not assigned string

because it number

is not assigned string

, and I think that is the expected behavior. But when I use a similar assignment with promises, the compiler doesn't throw an error. Is this normal or is this a bug?

function strOrNumFn (): string | number {
    return Math.random() > 0.5 ? 'some string' : 9;
}

const strOrNum = strOrNumFn();

// This fails as number is not assignable to string
const str: string = strOrNum;

// This fails same reason
const strA: Array<string> = [strOrNum];

// this doesn't fail, but I think it should
const strP: Promise<string> = Promise.resolve(strOrNum);

      

You can check the example with the TypeScript Playground .

Thanks in advance!

+3


source to share





All Articles