问题描述
我正在尝试将我的代码从 express 中的请求正文(使用正文解析器中间件)转换为接口,但它没有强制执行类型安全.
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 支持转换 但这仅适用于编译时间,并且你可以这样做:
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屋!
更多推荐
[db:关键词]
发布评论