【问题标题】:Only accept propertys inserted into an interface using typescript只接受使用打字稿插入接口的属性
【发布时间】:2021-07-04 03:15:49
【问题描述】:

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

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

【问题讨论】:

标签: node.js typescript express


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-29
    • 2021-02-02
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2019-02-10
    • 2018-04-12
    相关资源
    最近更新 更多