type OptionalKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? K : never
}[keyof T];
type FlipOptional<T> = (Required<Pick<T, OptionalKeys<T>>> &
Partial<Omit<T, OptionalKeys<T>>>) extends infer O
? { [K in keyof O]: O[K] }
: never;
Taken from https://stackoverflow.com/a/57593506/1154610.
A practical example is a TypeScript equivalent of ESLint rule react/require-default-props.
import React from 'react';
export interface InputProps {
className?: string;
name: string;
}
export default class Input extends React.Component<InputProps> {
static defaultProps: FlipOptional<InputProps> = {
// className is required for defaultProps.
className: null
// name is optional for defaultProps.
}
render() {
const { className, name } = this.props;
return <input className={className} name={name} />
}
}
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too