Looking to create a TypeScript function that removes a specific parameter foo
from an object and returns the modified object in a type-safe manner. Despite its apparent simplicity, I'm facing some challenges with the implementation. See my current code below:
interface FooProp {
foo: string;
}
type WithFooProp<P extends object> = P extends FooProp ? P : never;
type WithoutFooProp<P extends object> = P extends FooProp ? never: P;
function withoutFooProp<P extends object>(input: WithFooProp<P>): WithoutFooProp<P> {
// Eliminating any's
const {foo, ...withoutFoo} = input as any;
return withoutFoo as any;
}
I realize the excessive use of any
isn't ideal. Ideally, I would expect the code to function without it, but TypeScript complains about the inability to destructure input
as it's not recognized as an object. Any suggestions on enhancing this approach?
Furthermore, when using this function, TypeScript requires explicit definition of generic types. Is there a way to have these parameters inferred automatically? See examples below:
// Compiles - explicit prop types provided
withoutFooProp<{foo: string, bar: string}>({
foo: 'hi',
bar: 'hello',
});
// Doesn't compile - looking for a way to make it work implicitly
withoutFooProp({
foo: 'hi',
bar: 'hello',
});
Appreciate any help or advice!