简体   繁体   English

打字稿:另一个参数的关键?

[英]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?如何正确输入 Typscript? Is there a good way to use keyof a parameter like this?有没有像这样使用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];
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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