TypeScript type union requires length

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

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

This snippet compiles, but lengthis required lengthfor IMessage. If not specified, the error is:

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

I find this counterpoint because I need to make an assumption that it IMessagecan be used as an array type. Is adding the required length really, or am I making a mistake?

+4
source share
2 answers

There are currently no open issues with TypeScript 1.4 for Type Guard. Typical guards include both typeofand instanceof.

The function you are testing (instanceof) should lead to a narrowing of the type inside the if-block. This should mean that length?: string;your interface is not required.

, , , -.

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

, ( IMessage ).

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

Source: https://habr.com/ru/post/1569684/


All Articles