将对象转换为TypeScript中的接口 [英] Cast object to interface in TypeScript
问题描述
我试图将我的代码从express的请求正文(使用body-parser中间件)转换为接口,但这并没有强制类型安全。
I'm trying to make a cast in my code from the body of a request in express (using body-parser middleware) to an interface, but it's not enforcing type safety.
这是我的接口:
export interface IToDoDto {
description: string;
status: boolean;
};
这是我尝试执行转换的代码:
This is the code where I'm trying to do the cast:
@Post()
addToDo(@Response() res, @Request() req) {
const toDo: IToDoDto = <IToDoDto> req.body; // <<< cast here
this.toDoService.addToDo(toDo);
return res.status(HttpStatus.CREATED).end();
}
最后,被称为的服务方法:
And finally, the service method that's being called:
public addToDo(toDo: IToDoDto): void {
toDo.id = this.idCounter;
this.todos.push(toDo);
this.idCounter++;
}
我可以传递任何参数,甚至可以'接近匹配接口定义,并且此代码可以正常工作。我希望,如果不可能从响应主体到接口进行强制转换,则将在运行时抛出异常,例如Java或C#。
I can pass whatever arguments, even ones that don't come close to matching the interface definition, and this code will work fine. I would expect, if the cast from response body to interface is not possible, that an exception would be thrown at runtime like Java or C#.
我已经读到在TypeScript中不存在类型转换,只有类型声明,所以它只会告诉编译器对象的类型为 x
,所以...我错了吗?强制执行并确保类型安全的正确方法是什么?
I have read that in TypeScript casting doesn't exist, only Type Assertion, so it will only tell the compiler that an object is of type x
, so... Am I wrong? What's the right way to enforce and ensure type safety?
推荐答案
javascript中没有强制转换,因此如果投射失败,则无法抛出。
Typescript < href = https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions rel = noreferrer>支持转换,但这仅用于编译时间,您可以这样做:
There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:
const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;
您可以在运行时检查该值是否有效以及是否抛出错误,即:
You can check at runtime if the value is valid and if not throw an error, i.e.:
function isToDoDto(obj: any): obj is IToDoDto {
return typeof obj.description === "string" && typeof obj.status === "boolean";
}
@Post()
addToDo(@Response() res, @Request() req) {
if (!isToDoDto(req.body)) {
throw new Error("invalid request");
}
const toDo = req.body as IToDoDto;
this.toDoService.addToDo(toDo);
return res.status(HttpStatus.CREATED).end();
}
编辑
正如@huyz所指出的那样,不需要类型断言,因为 isToDoDto
是类型保护,所以这应该足够了:
Edit
As @huyz pointed out, there's no need for the type assertion because isToDoDto
is a type guard, so this should be enough:
if (!isToDoDto(req.body)) {
throw new Error("invalid request");
}
this.toDoService.addToDo(req.body);
这篇关于将对象转换为TypeScript中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!