简体   繁体   English

如何定义 Typescript 部分类型以仅接受属性

[英]How to define Typescript Partial type to accept only properties

Using Typescript 3.7.使用打字稿 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.现在在另一种方法中,我想声明一个参数是 Thing 的一部分,但应该只包含属性,而不是类。 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.当我使用Partial<Thing> ,也接受了我不想要的方法serialize

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.如果需要,您可以使用Partial<AcceptedType> 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:那么即使funcProp是“字段”或“属性”而不是method ,您也会同时排除methodfuncProp

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

So be warned.所以要小心。 Hope that helps;希望有所帮助; good luck!祝你好运!

Link to code 代码链接

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

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