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

时间:2019-12-10 16:50:48

标签: typescript

使用打字稿3.7。我有这堂课

class Thing {
  name: string;
  age: number;

  serialize() {}
}

现在在另一种方法中,我想声明参数是Thing的一部分,但应仅包括属性,而不包括类。所以我希望接受的类型是

{name: string, age: number}

这可能吗?当我使用Partial<Thing>时,不需要的方法serialize也被接受。

1 个答案:

答案 0 :(得分:2)

question this duplicates的回答显示了如何与conditional typesmapped types一起使用lookup types从对象中拉出仅匹配特定条件的属性。在您的情况下,这是我的处理方式:

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

如果需要,您可以使用Partial<AcceptedType>。需要注意的是,编译器无法真正分辨出方法函数值属性之间的区别。因此,如果您有类似的课程

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

然后,即使method是“字段”或“属性”而不是方法,您也将同时排除funcPropfuncProp

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

因此请注意。希望能有所帮助;祝你好运!

Link to code