为什么TypeScript不抱怨这个?

时间:2017-06-01 19:07:21

标签: generics es6-promise typescript-typings typescript2.0

在编译ES2015时,Promise键入了一个奇怪的行为。

在以下代码中,前两个分配(strstrA)无法抱怨 string | number无法分配给string 因为 number无法分配给string ,我认为这是预期的行为。但是当我使用promises使用类似的赋值时,编译器不会抛出错误。这是正常的还是一个错误?

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);

你可以test the example using the TypeScript Playground

提前致谢!

1 个答案:

答案 0 :(得分:0)

这应该可行:

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 | number  = strOrNum;

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

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