【问题标题】:How to define Typescript Partial type to accept only properties如何定义 Typescript 部分类型以仅接受属性
【发布时间】:2020-04-03 22:09:26
【问题描述】:

使用 Typescript 3.7。我有这门课

class Thing {
  name: string;
  age: number;

  serialize() {}
}

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

{name: string, age: number}

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

【问题讨论】:

标签: typescript


【解决方案1】:

question this duplicates 的答案展示了如何使用 conditional types 以及 mapped typeslookup 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&lt;AcceptedType&gt;。这里需要注意的是,编译器无法真正区分 方法函数值属性。因此,如果您有类似的课程

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

那么即使funcProp 是“字段”或“属性”而不是方法,您也会同时排除methodfuncProp

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

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

Link to code

【讨论】:

  • 我认为如果我不小心,陷阱会回来咬我。谢谢!
猜你喜欢
  • 2020-02-28
  • 2020-06-20
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
相关资源
最近更新 更多