我是打字新手,我正在尝试创建一个"模型";类。
构造函数应该接受一个属性列表(来自数据库),它们中的任何一个都应该是可选的。
下面是到目前为止的代码: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;
....
}
正如你所看到的,它看起来不对。很多代码是重复的。如果我想把属性设置为可选的它会复制更多的代码:(
谁能给我指个正确的方向?由于我建议从这里使用以下实用程序类型:
type NonFunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? never : K
}[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
这将在没有方法的class
的所有属性中创建type
。
你可以这样使用:
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
}
}
要使它们都是可选的,只需添加Partial
:
constructor({id, login, email, role }: Partial<NonFunctionProperties<User>>)
游乐场
我将如何实现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'
) {}
}
然而,如果你想从用户属性对象创建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);
}
}
没有优雅的方法来避免这种重复。Tobias S.和jcalz展示了避免这种重复的方法,但是我不建议您使用这种方法。