Reputation: 6623
I'm making a function that works with any object like this:
function deleteKey (obj, key) {
// This is just for an example, but you will get what kind of typing needed.
delete obj[key];
}
How can I give typing in Typscript correctly? Is there a good way to use keyof
a parameter like this?
function deleteKey (obj: object, key: keyof obj) {
// This is just for an example, but you will get what kind of typing needed.
delete obj[key];
}
Upvotes: 2
Views: 586
Reputation: 694
Something like this should do the trick:
function deleteKey<T, K extends keyof T>(obj: T, key: K): Omit<T, K> {
delete obj[key];
return obj;
}
interface Foo {
a: string;
b: number;
c: boolean;
}
const foo: Foo = { a: 'test', b: 12, c: true };
const foo_minus_a = deleteKey(foo, 'a');
const foo_minus_b = deleteKey(foo, 'b');
const foo_minus_c = deleteKey(foo, 'c');
Upvotes: 5