1

TLDR: Can't figure out how to solve the problem, a minimal example of which is reproduced on Try Flow. Please help.

Longer version

I have two properties that I am passing in a React object. Their combination makes them into three distinct types:

type BookResource = {|
  objectType: 'book',
  object: Book
|};

type AudiobookResource = {|
  objectType: 'audiobook',
  object: Audiobook
|};

type ComicbookResource = {|
  objectType: 'comicbook',
  object: Comicbook
|};

where

type Book = {
  foo: string
}

type Audiobook = {
  bar: string
}

type Comicbook = {
  baz: string
}

So I combine them into a single union type and intersect the result with the rest of the component's props:

type Resource = BookResource | AudiobookResource | ComicbookResource;

type Props = {
  text: string,
} & Resource;

I then want the component to behave in a particular manner depending on which member of the union was actually passed with the props:

class TestComponent extends Component<Props> {

  render() {
   return null; 
  }

  doMagic() {
    let { objectType, object } = this.props;

    if (objectType === 'book') {
      iWantBook(object)
    }
  }

}

function iWantBook(book: Book) {
 console.log(book.foo) 
}

Trouble is, Flow fails to see that if the objectType prop is of particular type, it means that the object prop is also of a specific type. It's trying to check the properties of all the members of the union and is giving me errors.

I am not sure whether it's a genuine Flow bug or whether something can be done with type declarations to make Flow distinguish between the members of the union.

1

1 Answer 1

2

try this

  1. You need to use type spread instead of an intersection type here.
  2. You can't use destructuring, see the issue
3
  • Example works nicely. Do you know why you can't use an intersection type for this? Apr 5, 2018 at 8:22
  • Wanted to ask you the same. Is this an expected behavior of Flow that intersection types do not work in this case, or is it a bug? (The docs about type spread you are linking to say that you can't intersect exact object types, but I was getting the same error even when I was declaring my types as regular objects).
    – azangru
    Apr 5, 2018 at 8:31
  • Unfortunately, I can't say is it a bug or not. With intersection type, you will get something like this in props: ``` { text: string, objectType: 'book' | 'audiobook' | 'comicbook', object: Book | Audiobook | Comicbook, } ```
    – Alex Savin
    Apr 5, 2018 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.