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

Viewed 103

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');
}
2 Answers

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

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

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