Search Terms
- object destructuring default value
- object destructuring default value property does not exist
- the title of the issue above
Suggestion
I would remove the following error:
function foo(bar: boolean) {
return {
a: 1,
b: 2,
...(bar && { c: 3 }),
};
}
const { a = 0, c = 0 } = foo(Math.random() < 0.5);
// ^ TS2339: Property 'c' does not exist on type '{ a: number; b: number; } | { c: number; a: number; b: number; }'.
console.log(a, c); // 1, 0 or 3
Use Cases
We use the pattern above for errors, dynamically adding a helper text when an error exists.
We would then like to do const { error, helperText = '' } = errorProps(...stuff).
As an alternative const { error, helperText } = errorProps(...stuff) (no default value) could/should also work (JS just sets it to undefined in this case.
Examples
export const errorProps = (field: FormField<unknown>, errorKey?: string) => {
const error = field.isDirty && field.errors.length > 0;
return {
error: error,
...(error && { helperText: i18n.t(errorKey ?? 'common.form.genericField.required') }),
};
};
// then
const { error, helperText = '' } = errorProps(field, errorKey);
Checklist
My suggestion meets these guidelines:
Search Terms
Suggestion
I would remove the following error:
Use Cases
We use the pattern above for errors, dynamically adding a helper text when an error exists.
We would then like to do
const { error, helperText = '' } = errorProps(...stuff).As an alternative
const { error, helperText } = errorProps(...stuff)(no default value) could/should also work (JS just sets it toundefinedin this case.Examples
Checklist
My suggestion meets these guidelines: