ke3pup
ke3pup

Reputation: 1895

Don't allow use of non existent keys on a given flow type

given this simple object: { id: 'x', value: 1 }, in TypeScript if you try to do:

type foo = {
    id: string,
    v: number,
};

const bar: foo = { id: 'something', v: 1111 };

// refrencing non existent key
if (bar.xyz) {
    console.log('xyz'); 
}

you would get an error saying xyz does not exist on foo. How do you get the same result on Flowjs?

I've tried the following but flowjs isn't throwing any errors:

type foo = {|
    id: string,
    v: number,
|};

const bar: foo = { id: 'something', v: 1111 };


if (bar.xyz) { // no errors
    console.log('xyz');
}

Upvotes: 4

Views: 131

Answers (2)

artgb
artgb

Reputation: 3233

Your problem is still exist as an open issue. https://github.com/facebook/flow/issues/106

As long as that issue is open, you can forcefully do type conversion bar.xyz to Boolean.

if (Boolean(bar.xyz))

You will get this error.

10: if (Boolean(bar.xyz)) { ^ property xyz. Property not found in

10: if (Boolean(bar.xyz)) { ^ object type

Upvotes: 1

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220954

Flow always allows for property checks in ifs. You can use this as a workaround:

if (!!bar.xyz == true) {

Upvotes: 0

Related Questions