在编译ES2015时,Promise键入了一个奇怪的行为。
在以下代码中,前两个分配(str
和strA
)无法抱怨 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。
提前致谢!
答案 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);