Search code examples
javascriptflowtypeflow-typed

Assume value exists if another value exists in Flow type checking


I'm trying to figure out if this is possible with flow.

I have a function that returns an object like this

{
  isChannel: boolean,
  channelName?: string,
  streamName?: string,
}

if isChannel === true, I know channelName will exist.

In many places in our codebase we have something like this

const { channelName, streamName, isChannel } = parseUri(uri);
const name = isChannel ? channelName.slice(1) : streamName;

The slice(1) is because the channelName includes a leading @. I know there are ways around this, but since this is all existing code, I'd rather not have to change it all.

Is there anyway to say this with flow types? If isChannel is true, channelName will exist, if isChannel is false, then it might exist.

if isChannel === true
then channelName: string
else channelName?: string

Solution

  • You can define a union type where one type has isChannel: true and the other has isChannel: false:

    type Channel = 
      | {| isChannel: false, channelName?: string, streamName?: string |}
      | {| isChannel: true, channelName: string, streamName?: string |};
    

    Try Flow

    Then you can refine the type by checking isChannel without having to check channelName.