Skip to content

Object destructuring: don't throw when property exists in any union type and default value is set #41080

@sandrosc

Description

@sandrosc

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:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions