只接受使用打字稿插入接口的属性

时间:2021-07-02 16:40:29

标签: node.js typescript express

我最近开始使用 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 中声明的属性

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

1 个答案:

答案 0 :(得分:0)

我认为你做不到。有 a way to do this with object literals,但有 you can always pass a pre-created object, avoiding the error

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