In TypeScript, you can combine two interface types like this
interface Foo {
var1: string
}
interface Bar {
var2: string
}
type Combined = Foo & Ba
There is utility-types library that has Subtract
mapped type:
import { Subtract } from 'utility-types';
type Props = { name: string; age: number; visible: boolean };
type DefaultProps = { age: number };
type RequiredProps = Subtract<Props, DefaultProps>;
// Expect: { name: string; visible: boolean; }
In TypeScript 2.8 you can now do the following:
interface Foo {
attribute1: string;
optional2?: string;
excludePlease: string;
}
// Typescript 3.5+ defines Omit for you.
// In earlier Typescript versions define Omit:
// type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
// Use Omit to exclude one or more fields (use "excludePlease"|"field2"|"field3" etc to exclude multiple)
type Bar = Omit<Foo, "excludePlease">
const b: Bar = {
attribute1: ''
};
So in relation to your question the following might be what you want:
export default function valueHOC<P> (
Comp: React.ComponentClass<P> | React.StatelessComponent<P>
): React.ComponentClass<Omit<P, "value">> {
return class WrappedComponent extends React.Component<Omit<P, "value">, State> {
render () {
return (
<Comp
{...this.props}
value={this.state.value}
/>
)
}
}
interface MyDialogProps extends Omit<DialogProps, 'onClose'> {
id: string;
onClose: (reason: string) => void;
}
export const MyDialog: React.FC<MyDialogProps> = ({ id, onClose, ...props) => (
<Dialog onClose={() => onClose("whatever")} {...props} />
);
You can't remove properties from already existing interfaces. Even trying to extend existing interface with the interface having value
property set as optional will return an error.
To avoid this issue, modify the typings of the target component so value
property is optional.
e.g.
// ...
class MyComponent extends React.Component<{value?: string}, State> {
// ...
}
and then component produced when using High Order Function
const valuedComponent = valueHOC(MyComponent);
won't ask for value
prop.