我正在创建一个可与任何对象一起使用的函数:
function deleteKey (obj, key) {
// This is just for an example, but you will get what kind of typing needed.
delete obj[key];
}
如何正确输入Typscript?有没有使用keyof
这样的参数的好方法?
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];
}
答案 0 :(得分:3)
类似这样的事情应该可以解决:
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');