1

This question is similar to this question, but not similar enough for me to understand how to do it.

I want to copy a type, but exclude all the methods from it.

interface XYZ {
  x: number;
  y: string;
  z(): void;
}

So z would be excluded and I would end up with:

interface XY {
  x: number;
  y: string;
}

I know that it's possible to do:

type OmitZ = Omit<XYZ, "z">;

But I don't want to omit based on key string, but based on property type. Is that even possible?

Evert
  • 2,022
  • 1
  • 20
  • 29

1 Answers1

3

Try this:


type ExcludeFunctionKeys<T> = Pick<
  T,
  { [K in keyof T]: T[K] extends (...args: any) => any ? never : K }[keyof T]
>

type XY = ExcludeFunctionKeys<XYZ>

Pritam Kadam
  • 2,388
  • 8
  • 16
  • Hey, I have 2 follow-up questions. I've found that this trick works nicely for optional class props, in that it makes them optional in the type too. However, that doesn't work for class props that have a default value. I would also like those to become optional in the resulting type. Is that possible? I can imagine it might not be, but I thought I'd ask anyway. And finally, I see that this trick doesn't exclude getters and setters yet. Is there a way to exclude those too? – Evert Sep 15 '20 at 09:15