简体   繁体   中英

Typescript: keyof another parameter?

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];
}

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM