Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从类中排除getter以创建存储库?_Javascript_Mongodb_Typescript - Fatal编程技术网

Javascript 如何从类中排除getter以创建存储库?

Javascript 如何从类中排除getter以创建存储库?,javascript,mongodb,typescript,Javascript,Mongodb,Typescript,我有这门课: export class User{ fName: string; lName: string; get FullName() { return this.fName + ' ' + this.lName } } 我创建了用户的集合: cost userRepo = this.connection.db(db).collection<User>(db) cost userRepo=this.connection.db(db).collecti

我有这门课:

export class User{
    fName: string;
    lName: string;
    get FullName() { return this.fName + ' ' + this.lName }
}
我创建了
用户的集合

cost userRepo = this.connection.db(db).collection<User>(db)
cost userRepo=this.connection.db(db).collection(db)
问题是,当我执行
userRepo.find({})
时,我可以将
FullName
作为参数发送


所以,我的问题是,有一种简单的方法可以从现有类中创建新类型,排除getter/setter吗?(没有创建接口或基类…

不太可能。该类只是要创建的对象的蓝图。上面的类将被编译成javascript中的函数构造函数,并且将始终包含最初提供给它的所有属性。

在类型级别,您无法真正区分属性和getter/setter。因此,正如其他人所说,你的问题的简短答案是“不”

对于您来说,一种可能的方法是注意到一个具有getter但没有setter的属性最终会被视为一个属性。事实证明,您可以使用一些疯狂的类型操纵魔法,创建一个类型函数,它可以提取出
只读
属性:

// 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];
//检测两种类型X和Y是否完全相同
IfEquals类型=
(()=>T扩展X?1:2)扩展
(()=>T扩展Y?1:2)?A:B;
//可写键是那些在去掉readonly时完全相等的键
//在映射类型中
类型可写键={
[P in keyof T]-?:如果等于
}[keyof T];
以及您要找的类型:

type UserWithoutGetters = Pick<User, WritableKeys<User>>;
// type UserWithoutGetters = {
//   fName: string;
//   lName: string;
// }    
键入UserWithoutGetters=Pick;
//类型UserWithoutGetters={
//fName:字符串;
//lName:字符串;
// }    

这有用吗?祝你好运

我在搜索像keyof这样的东西,只是没有getter/setter,这是不一样的。这将帮助您组合不同的类型,但不排除它们的任何属性是的!谢谢。在“[P in keyof T]-”和-readonly中连字符是什么意思?它是。