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:
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:
You might ask "why not just manually mark the parameter as optional?" Good question! Because:
Use Cases
React function components are a very common use case for "named parameters" and destructuring with defaults.
(
defaultPropsis 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: