gpt4 book ai didi

typescript :另一个参数的键?

转载 作者:行者123 更新时间:2023-12-02 03:03:36 26 4
gpt4 key购买 nike

我正在创建一个适用于任何对象的函数,如下所示:

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

最佳答案

像这样的事情应该可以解决问题:

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

关于 typescript :另一个参数的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59494896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com