以下代码会导致编译错误,即使它看起来是正确的:
type Name = { name: string };
type NamePlus = { name: string, hair: string };
type ReturnType = { foo: Name, bar: NamePlus };
export async function test(): Promise<ReturnType> {
const myName: Name = { name: 'Tom' };
const myNamePlus: NamePlus = { name: 'Larry', hair: 'black' };
const result = await Promise.all([myName, myNamePlus]);
return {
foo: result[0],
bar: result[1],
};
}
TS错误是:
Type '{ foo: Name; bar: Name; }' is not assignable to type 'ReturnType'.
Types of property 'bar' are incompatible.
Type 'Name' is not assignable to type 'NamePlus'.
Property 'hair' is missing in type 'Name'.
结构子类型似乎出现了问题,但我并不清楚究竟是什么导致了这个错误。我喜欢解释。
答案 0 :(得分:0)
此错误仅发生在Typescript 2.4中。最新版本的Typescript解决了这个问题。