TypeScript联合类型需要长度

时间:2015-01-02 10:05:01

标签: typescript

interface IMessage {
  value: string;
  length?: string;   // <-- why is this line necessary?
}

function saySize(message: IMessage|IMessage[]) {
  if (message instanceof Array) {
    return message.length;
  }
}

此代码段已编译,但在length中需要选项IMessage。如果省略,则错误为:

unions.ts(8,24): error TS2339: Property 'length' does not exist on type 'IMessage | IMessage[]'.

我发现这违反直觉,因为我需要假设IMessage可以用作数组类型。是否确实需要添加可选长度,或者我犯了错误?

2 个答案:

答案 0 :(得分:3)

好像是一个Bug。我已在此处报告:https://github.com/Microsoft/TypeScript/issues/1587需要注意的是,我不会将interface与Type Guard一起使用,尽管这不是此处错误的来源。

更新已修复masterhttps://github.com/Microsoft/TypeScript/pull/1657,因此应该在1.4

答案 1 :(得分:2)

针对Type Guard的TypeScript 1.4目前尚未解决。类型警卫包括typeofinstanceof

您使用的检查(instanceof)应该会导致if-block中的类型变窄。这应该意味着您的界面上不需要length?: string;

您可以在此处提出问题,看看是否可以修复,或者是否有特殊原因可以对数组进行不同的处理。

https://github.com/Microsoft/TypeScript/milestones/TypeScript%201.4

与此同时,您可以使用这种难看的类型断言来避免将属性添加到您的接口(因为IMessage不具有该属性)。

return (<IMessage[]><any>message).length;