I am trying to define an input type to a function that may contain fields defined by a type Foo.
interface Foo {
foo: string;
}
function baz<T extends Partial<Foo>>(x: T) {
return x;
}
// ok:
const args1 = { foo: '1', bar: 1 };
baz(args1);
// error: Type '{ bar: number; }' has no properties in common with type 'Partial<Foo>'
const args2 = { bar: 1 };
baz(args2);
Whatever else x
has, I want to specify that it may have foo
as defined in interface Foo
, but it may not, and that’s ok.
In my real-world example, it’s a few different fields, not just the one. Specifically, I’m writing a function that takes some React props for an arbitrary component that may include className
, style
and a few others, as defined by a specific interface. The function merges these props with required props for a child component to return the final set of modified props for the child component.
function mergeDraggableProps<T extends Partial<DraggableChildProps>>(
draggableProps: DraggableChildProps,
childProps: T
): T & DraggableChildProps {
return {
...childProps,
className: cn(draggableProps.className, childProps.className),
style: {
...draggableProps.style,
...childProps.style,
},
transform: draggableProps.transform,
onMouseDown: draggableProps.onMouseDown,
onMouseUp: draggableProps.onMouseUp,
onTouchEnd: draggableProps.onTouchEnd,
};
}
I can call this function with desired props that include className
, but as soon as I remove it TypeScript errors for the same reason:
… has no properties in common with type ‘Partial<DraggableChildProps>’.
How can I make it valid even if childProps
contains none of the fields of DraggableChildProps
? (In the simplified example, if x
contains none of the fields of Foo
?)