I'd like to write a typescript function that takes an object that includes the parameter foo and outputs the same object without the parameter foo. I want to do this all in a typesafe manner. Seems pretty simple, but I'm stumbling. Here is the code I have so far:
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> {
// How do I get rid of these any's
const {foo, ...withoutFoo} = input as any;
return withoutFoo as any;
}
This isn't great because I use any a bunch. I'd sorta expect the code to work as is without any, but TS complains that input isn't an object and can't be destructured. How could I improve this method?
In addition, when I use this function, TS forces me to provide the generic types explicitly. I wish it would infer the types implicitly. Is there any way I could write the function to implicitly grab the parameters.
// Compiles - but I have to specify the props explicitly
withoutFooProp<{foo: string, bar: string}>({
foo: 'hi',
bar: 'hi',
});
// This doesn't compile - I wish it did! How can I make it?
withoutFooProp({
foo: 'hi',
bar: 'hi',
});
Thanks in advance!