我试图在我的代码中从express中的请求主体(使用主体解析器中间件)转换到接口,但它没有强制执行类型安全.
这是我的界面:
export interface IToDoDto {
description: string;
status: boolean;
};
这是我试着做演员的代码:
@Post()
addToDo(@Response() res, @Request() req) {
const toDo: IToDoDto = <IToDoDto> req.body; // <<< cast here
this.toDoService.addToDo(toDo);
return res.status(HttpStatus.CREATED).end();
}
最后,要调用的服务方法:
public addToDo(toDo: IToDoDto): void {
toDo.id = this.idCounter;
this.todos.push(toDo);
this.idCounter++;
}
I can pass whatever arguments, even ones that don't come close to matching the interface definition, and this code will work fine.我预计,如果从响应体到接口的转换不可能,那么会在运行时抛出一个异常,比如Java或C#.
我已经读到在类型脚本中不存在强制转换,只有类型断言,所以它只会告诉编译器一个对象是类型x
,所以...我错了吗?实施和确保类型安全的正确方法是什么?