[英]Model class constructor in Typescript
I am new to typescript and I am trying to create a "model" class.我是打字稿的新手,我正在尝试创建一个“模型”类。
The constructor should accept a list of properties (that come from the database), and any of them should be optional.构造函数应该接受一个属性列表(来自数据库),并且它们中的任何一个都应该是可选的。
Here is the code so far:这是到目前为止的代码:
export type UserRole = "admin" | "moderator" | "user" | "visitor";
export default class User{
public id: number | null = null;
public login: string = '';
public email: string = '';
public role: UserRole = 'visitor';
...
constructor({id, login, email, role, ... }){
this.id = id;
this.login = login;
this.email = email;
this.role = role;
....
}
As you can see, it doesn't look right.如您所见,它看起来不正确。 A lot of code is duplicated.很多代码是重复的。 And if I want to make the properties optional it will duplicate even more code:(如果我想让属性成为可选的,它将复制更多的代码:(
Can anyone point me in the right direction?谁能指出我正确的方向? thanks谢谢
I would suggest to use following utility type from here :我建议从这里使用以下实用程序类型:
type NonFunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? never : K
}[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
This will create a type
out of all properties of a class
without the methods.这将在没有方法的class
的所有属性中创建一个type
。
You can use it like this:你可以像这样使用它:
export type UserRole = "admin" | "moderator" | "user" | "visitor";
export default class User{
public id: number | null = null;
public login: string = '';
public email: string = '';
public role: UserRole = 'visitor';
constructor({id, login, email, role }: NonFunctionProperties<User>){
this.id = id;
this.login = login;
this.email = email;
this.role = role
}
}
To make them all optional, just add Partial
:要使它们全部可选,只需添加Partial
:
constructor({id, login, email, role }: Partial<NonFunctionProperties<User>>)
Here's how I would implement the User
class.下面是我将如何实现User
类。
type UserRole = 'admin' | 'moderator' | 'user' | 'visitor';
class User {
constructor(
public id: number | null = null,
public login: string = '',
public email: string = '',
public role: UserRole = 'visitor'
) {}
}
However, if you want to create the instance of the User
class from an object of user properties then you will require some duplication.但是,如果您想从用户属性的对象创建User
类的实例,那么您将需要一些重复。
type UserRole = 'admin' | 'moderator' | 'user' | 'visitor';
interface UserProps {
id: number | null;
login: string;
email: string;
role: UserRole;
}
class User implements UserProps {
constructor(
public id: number | null = null,
public login: string = '',
public email: string = '',
public role: UserRole = 'visitor'
) {}
static fromProps({ id, login, email, role }: Partial<UserProps> = {}) {
return new User(id, login, email, role);
}
}
There's no elegant way around this duplication.这种重复没有优雅的方法。 Tobias S. and jcalz show hacks to avoid this duplication, but I would discourage you from using such hacks. Tobias S.和jcalz展示了避免这种重复的技巧,但我不鼓励你使用这种技巧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.