简体   繁体   中英

How to define Typescript Partial type to accept only properties

Using Typescript 3.7. I have this class

class Thing {
  name: string;
  age: number;

  serialize() {}
}

Now in another method I want to declare that an argument is a partial of Thing, but should only include properties, not class. So I want the accepted type to be

{name: string, age: number}

Is this possible? When I use Partial<Thing> , the method serialize is also accepted which I don't want.

The answers to the question this duplicates show how to use conditional types along with mapped types and lookup types to pull just properties matching a certain criterion out of an object. Here's how I'd do it in your case:

type ExcludeFunctionProps<T> =
    Omit<T, { [K in keyof T]-?: T[K] extends Function ? K : never }[keyof T]>

type AcceptedType = ExcludeFunctionProps<Thing>;
/*
type AcceptedType = {
    name: string;
    age: number;
}
*/

And you could use Partial<AcceptedType> if you want that. A caveat here is that the compiler can't really tell the difference between methods and function-valued properties . So if you had a class like

class Stuff {
    name: string = "";
    method() { }
    funcProp: () => void = () => console.log("oops");
}

then you'd be excluding both method as well as funcProp even though funcProp is a "field" or "property" and not a method:

type SomeStuff = ExcludeFunctionProps<Stuff>;
// type SomeStuff = {name: string}

So be warned. Hope that helps; good luck!

Link to code

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