简体   繁体   English

如何在Typescript中定义拒绝来自对象的键的通用函数?

[英]How to define generic function rejecting key from object in Typescript?

I'm trying to define a utility function to clean up objects of specific keys.我正在尝试定义一个实用程序函数来清理特定键的对象。

/**
 * Strip all the __typenames from the payload.
 */
interface WithTypename {
  __typename?: string;
};

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

const omitTypename = <T extends WithTypename>({ __typename, ...rest }: T): Omit<T, '__typename'> => ({ ...rest });

But compiler complains on the function parameters that { __typename, ...rest } .但是编译器抱怨{ __typename, ...rest }的函数参数。 Rest types may only be created from object types.休息类型只能从对象类型创建。

This is a known limitation of spread in Typescript, there are multiple issues on it here is a recent one.这是打字稿传播的一个已知的限制,有多个问题上这里是最近的一个。

One possible workaround is to use Object.assign and then delete the extra property.一种可能的解决方法是使用Object.assign ,然后删除额外的属性。

/**
 * Strip all the __typenames from the payload.
 */
interface WithTypename {
__typename?: string;
};

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

const omitTypename = <T extends WithTypename>(o: T): Omit<T, '__typename'> => {
    let r = Object.assign({}, o);
    delete r.__typename;
    return r;
}

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

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