我正在TypeScript中编写一些代码,通过将对象中的所有属性设置到类中,将一些非类型化对象(可能是某种JSON(转换为类型化类。如果非类型化对象没有我在类中查找的属性,我想抛出一个错误。
我在TypeScript中寻找一种简洁的方法,并想出了这个。据我所知,它是有效的,但对我来说,它感觉有点粗糙。我想知道其他开发人员是否知道这样做的既定方式,或者这是否可以
const invalid = () => {throw new Error("Invalid input given in User.")}
this.firstName = obj.firstName ?? invalid();
this.lastName = obj.lastName ?? invalid();
this.email = obj.email ?? invalid();
或者,如果有人知道将非类型化对象转换为类的更简单方法,我会洗耳恭听。
我遇到的最通用的方法是定义类型保护函数。例如(TypeScript Playground:
interface IUser {
firstName: string;
lastName: string;
email: string;
}
function isIUser(potentialIUser: any): potentialIUser is IUser {
return "firstName" in potentialIUser && "firstName" in potentialIUser && "firstName" in potentialIUser;
}
class User implements IUser {
public firstName: string;
public lastName: string;
public email: string;
constructor(user: IUser) {
if(!isIUser(user)){
throw new TypeError("Provided user is not compatible with interface IUser");
}
this.firstName = user.firstName;
this.lastName = user.lastName;
this.email = user.email;
}
}
async function whoAmI(): Promise<User> {
const user: IUser = await (await fetch("example.com/api/user/me")).json();
return new User(user);
}
这给了你三个优势:
- 方便的是,如果您有像
AuthenticatedUser | GuestUser
这样的联合,那么您已经有了一个函数来确定它是什么 - 使用
TypeError
会给JS带来完全相同的错误,并且没有依赖关系 - 这也为您提供了从其他来源构造
Users
的函数,只需进行最小的更改