只接受使用typescript插入接口的属性



我最近开始了使用typescript的旅程,我正在使用express+typescript开发一个应用程序。

我有这个控制器:

import { Request, Response } from 'express'
import PartialUserUpdateService from '../services/PartialUserUpdateService'
class PartialUserUpdateController {
async handle (request: Request, response: Response): Promise<Response> {
const id : number = +request.params.id
const partialUserContent = request.body
const partialUserUpdateService = new PartialUserUpdateService()
const user = await partialUserUpdateService.execute({ userId: id, partialUserContent })
return response.status(200).json(user)
}
}
export default new PartialUserUpdateController()

这项服务:

import { getRepository } from 'typeorm'
import UserSchema from '../entities/user.schema'
interface IPartialUserUpdate {
name?: string;
email?: string;
age?: number;
cpf?: string;
}
interface IPartialUserDTO {
userId: number;
partialUserContent: IPartialUserUpdate;
}
class PartialUserUpdateService {
async execute ({
userId,
partialUserContent
}: IPartialUserDTO): Promise<IPartialUserUpdate> {
const userRepository = getRepository(UserSchema)
const user = await userRepository.findOne(userId)
if (!user) throw new Error('User doesnt exists')
await userRepository.update({ id: user.id }, userContent)
return partialUserContent
}
}
export default PartialUserUpdateService

我试图使partialUserContent对象只能接收在接口IPartialUserUpdate中声明的属性

如何显式检查属性和类型,并在任何类型不同时报告错误?

我认为你做不到。有一种方法可以使用对象文字来实现这一点,但您总是可以传递预先创建的对象,从而避免错误。

TypeScript中的此类类型保护旨在确保以后使用此类值时不会导致任何愚蠢的错误。换句话说,如果您的函数使用foo.prop,那么foo最好具有属性prop,其他所有内容都在类型保护的范围之外。

最新更新