Reputation: 20007
I'm trying to access a field on an object that I believe should always exist.
How can the following flow error be resolved?
problem = (arg: {refKey: string} = {}) => {
const {refKey = 'ref', ...rest} = arg;
return {
[refKey]:arg[refKey],
...rest
};
};
19: [refKey]:arg[refKey],
^ Cannot get `arg[refKey]` because property `ref` is missing in object type [1].
References:
16: problem = (arg: {refKey: string} = {}) => {
^ [1]
Upvotes: 0
Views: 68
Reputation:
It's happening because you are setting the value when you are declaring it.
If you want to set a default value, you can set it in the default parameter, like so:
problem = (arg: {refKey: string} = {refKey: 'ref'}) => {
const {refKey, ...rest} = arg;
return {
[refKey]:arg[refKey],
...rest
};
};
EDIT
Okay, I think I misunderstood the problem and have now understood it (!).
If the default property will be named 'ref'
, you can do this:
problem = (arg: {refKey: string, ref: any} = {}) => {
const {refKey = 'ref', ...rest} = arg;
return {
[refKey]:arg[refKey],
...rest
};
};
Upvotes: 1