简体   繁体   中英

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 } . 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.

/**
 * 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;
}

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