T.Chmelevskij
T.Chmelevskij

Reputation: 2139

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.

Upvotes: 1

Views: 217

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250416

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

Upvotes: 1

Related Questions