Skip to content

Suggestion: automatically mark named parameters with defaults as optional #30488

@OliverJAsh

Description

@OliverJAsh

Search Terms

default destructuring named parameters object optional automatically

Suggestion

When using "named parameters", if a parameter has a default (provided when destructuring), TypeScript should automatically mark that named parameter as optional. Example:

const myFn = ({ foo, bar = 'default' }: { foo: number; bar: string; }) => {
    bar
}

// No error since `bar` is marked as automatically optional.
// (Currently this errors because `bar` is still marked as required.)
myFn({ foo: 1 });

You might ask "why not just manually mark the parameter as optional?" Good question! Because:

  • When modifying defaults, we must remember to manually modify the parameter types to match any defaults we have added/removed.
  • Sometimes the parameter types are not easily modifyable, e.g. when it comes from a third party (example below).
// We can't easily modify `SomeThirdPartyObject` here to mark `bar` as optional.
const myFn = ({ foo, bar = 'default' }: SomeThirdPartyObject) => {}
// Workaround
const myFn = ({ foo, bar = 'default' }: Omit<SomeThirdPartyObject, 'bar'> & Partial<Pick<SomeThirdPartyObject, 'bar'>>) => {}
myFn({ foo: 1 })

Use Cases

React function components are a very common use case for "named parameters" and destructuring with defaults.

import * as React from 'react';

type Props = { foo: number; bar: string; };

const MyComponent: React.FunctionComponent<Props> = ({
    foo,
    bar = 'default',
}) => null;

// No error since `bar` is marked as automatically optional.
// (Currently this errors because `bar` is still marked as required.)
<MyComponent foo={1} />;
const MyComponent = ({
    foo,
    bar = 'default',
}: Props) => null;

// No error since `bar` is marked as automatically optional.
// (Currently this errors because `bar` is still marked as required.)
<MyComponent foo={1} />;

(defaultProps is supposed to solve this exact problem, but it doesn't currently work for function components: DefinitelyTyped/DefinitelyTyped#30695).

Examples

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

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions