Skip to content

Optional properties with object shorthand syntax #39376

Closed
@danielrentz

Description

@danielrentz

Search Terms

object shorthand optional

Suggestion

Allow to specify optional properties in object shorthand syntax. If the variable is undefined, the property will not be added to the object (instead of being added with value undefined). Proposed syntax is to add a question mark to the property name, for example { prop1, prop2? }.

Use Cases

Goal is to create one object with a short clear (one-line) syntax.

On StackOverflow, this issue is discussed here: https://stackoverflow.com/questions/54909137/how-to-conditionally-set-optional-properties
The proposed solution uses object spread syntax. But this may have performance impact (temporary objects, property iteration) and is way too verbose.

Examples

interface Test {
  required: number;
  optional?: number
}
let required = 42;
let optional: number | undefined;

Current solution:

const object: Test = { required };
if (optional !== undefined) { object.optional = optional; }

Proposed solution:

const object: Test = { required, optional? };

The compiler would convert this to the solution above with if statements as needed.

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.

I have no idea about the last point though... :/ At least I did not find a comparable ES proposal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions