[英]How to get returned class properties when passing as argument in typescript
I having issue with getting properies of class when I'm passing that as parameter in another class method当我将它作为另一个类方法中的参数传递时,我在获取类属性时遇到问题
My issue is so complicted in my code and I tried to simplified it to get the solution我的问题在我的代码中非常复杂,我试图简化它以获得解决方案
imagine I have class as User like this:想象一下我有像这样的用户类:
class User {
name!:string
static setName(_name:string){
const user = new User()
user.name = _name
return user
}
}
and Company with almost same properties:和具有几乎相同属性的公司:
class Company {
name!:string
brand!:string = 'mtx'
static setName(_name:string){
const company = new Company()
company.name = _name
return company
}
}
and I have Registration Class that has register method:我有注册类有注册方法:
class Registration {
static register<K >(name:string,Model: K & { setName:(n:string)=>K}): K{
return Model.setName(name)
}
}
and I register user and company in this way:我以这种方式注册用户和公司:
let user = Registration.register('mamad',User)
let company = Registration.register('mamad',Company)
so this is working for user but for company returns this error:所以这对用户有用,但对公司来说会返回此错误:
and here is playground这里是游乐场
You can just remove the K &
so it will look like this:你可以只删除
K &
所以它看起来像这样:
class Registration {
static register<K >(name:string,Model: { setName:(n:string)=>K}): K{
return Model.setName(name)
}
}
When you are calling:当你打电话时:
let company = Registration.register('mamad',Company)
You are not supplying K
argument, you are only basically supplying the setName
, because that is present as static property.您不提供
K
参数,您基本上只提供setName
,因为它作为静态属性存在。 If you would have the K &
part, then you would need to be supplying actual instance, new Company()
or such in order to be able to refer to instance fields.如果您有
K &
部分,那么您需要提供实际实例、 new Company()
等,以便能够引用实例字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.