Kasper
Kasper

Reputation: 13582

How do I make types that can only contain certain properties in flow?

I have some code like this:

/* @flow */

type Options = {
  userdir?: string,
}

function foo(options: Options) {
  return 'foo';
}

foo({userDir: 'bar'});

I expected that flow would warn me here, that there is no property userDir in my Options type. But according to the flow type checker, this code is totally fine. How do I make types that can only have certain properties in flow?

Upvotes: 0

Views: 79

Answers (1)

Kamek
Kamek

Reputation: 58

In your snippet, you're declaring an optional property, so Flow doesn't complain.

If you need Flow to tell you about the missing property, you need to remove the question mark :

type Options = {
    userdir: string;
};

If you need that property to be defined, but also allow it to be null or undefined, you can use a 'maybe type' :

type Options = {
    userdir: ?string;
};

edit : We discussed this on Reactiflux, turns out Flow (as of 0.32) just added Exact types :

type Options = {|
    userdir: ?string;
|};

Using this syntax, when calling foo({userDir: 'bar'}); Flow will complain about the userDir property, which does not exist in the above definition.

Upvotes: 3

Related Questions