如何从类中排除吸气剂以创建存储库?

时间:2019-02-19 16:04:41

标签: javascript mongodb typescript

我上了这个课:

export class User{
    fName: string;
    lName: string;
    get FullName() { return this.fName + ' ' + this.lName }
}

然后我创建了User的集合:

cost userRepo = this.connection.db(db).collection<User>(db)

问题在于,当我执行userRepo.find({})时,我可以发送FullName作为参数。

所以,我的问题是,有一种简单的方法可以从现有的类中创建新类型,但不包括getter / setter? (没有创建接口或基类...)

2 个答案:

答案 0 :(得分:1)

您不能真正在类型级别将属性与getter / setter区别开。因此,正如其他人所说,对您的问题的简短回答是“否”。

一种可能的 方法是,将带有吸气剂但没有setter的属性最终视为readonly。事实证明,您可以 使用一些疯狂的类型操作魔术来创建一个可以提取readonly属性的类型函数:

// detect if two types X and Y are exactly identical
type IfEquals<X, Y, A=X, B=never> =
  (<T>() => T extends X ? 1 : 2) extends
  (<T>() => T extends Y ? 1 : 2) ? A : B;

// writable keys are those which are exactly equal when you strip readonly off
// in a mapped type
type WritableKeys<T> = {
  [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
}[keyof T];

以及您要查找的类型:

type UserWithoutGetters = Pick<User, WritableKeys<User>>;
// type UserWithoutGetters = {
//   fName: string;
//   lName: string;
// }    

有帮助吗?祝你好运!

答案 1 :(得分:0)

不是。该类只是您将要创建的对象的蓝图。上面的类将被编译为javascript中的函数构造函数,并将始终包含最初赋予它的所有属性。

相关问题