jacobsowles
jacobsowles

Reputation: 3003

How to check if an object is an instance of a Flow type?

I have two Flow types set up:

type Form1Fields = {
    fieldA
}

type Form2Fields = {
    fieldZ
}

type FormFields = Form1Fields | Form2Fields

Then I function that accepts a FormFields object as a parameter:

const myFunction = (fields: FormFields) => return fields.fieldA;

That's giving me the error Cannot get fields.fieldA because property fieldA is missing on Form2Fields.

I get what it's saying. According to the Flow docs, "when calling our function that accepts a union type we must pass in one of those types. But inside of our function we are required to handle all of the possible types."

So in myFunction, I'd need to do something like:

if (typeof fields === Form1Fields) { ... }
else { ... }

I could do that with primitive types like number, but it doesn't seem like I can do that with Flow types.

Is there a way to compare an object to Flow types, or is there a different way of solving this problem?

Upvotes: 4

Views: 1795

Answers (1)

jacobsowles
jacobsowles

Reputation: 3003

Ah, the answer is Disjoint Unions. By adding a field to a type that "identifies" that type, I can check for it in myFunction.

type Form1Fields = {
    type: 'Form1Fields',
    fieldA: string
}

type Form2Fields = {
    type: 'Form2Fields',
    fieldZ: string
}

type FormFields = Form1Fields | Form2Fields

const myFunction = (fields: FormFields) => return fields.type === 'Form1Fields' ? fields.fieldA : fields.fieldZ;

Upvotes: 5

Related Questions