Express TypeScript:为什么我的控制器方法抛出错误消息?

时间:2019-04-03 14:47:00

标签: javascript node.js typescript

人。我只是刚开始使用TypeScript,因此,弄湿我的一部分包括将我构建的Express后端转换为TS。到目前为止,一切都很好,但是现在我遇到了一些非常不寻常的问题。具体来说,以下代码段中的行const hasVoted = poll.votedBy.some((voter): boolean => voter.equals(voterId));const choice = await poll.choices.id(choiceId);分别导致Property 'equals' does not exist on type 'string'Property 'choices' does not exist on type 'Poll & Document'错误消息。作为参考,我的JS版本工作正常,那么这里可能缺少什么呢?

后置控制器

import * as mongoose from 'mongoose';
import { Request, Response } from 'express';

import { Poll } from '../models/index';

class PollsController {
  public async addNewPoll(req: Request, res: Response) {
    // ...
  }

  public async voteInPoll(req: Request, res: Response) {
    const { category, pollId } = req.params;
    const { name, choiceId, voterId } = req.body;

    try {
      const poll = await Poll.findById(pollId);

      // Check if user has already voted in poll
      const hasVoted = poll.votedBy.some((voter): boolean => voter.equals(voterId));

      if (!voterId) {
        res
          .status(401)
          .json({ message: 'Sorry, you must be logged in to vote' });
      } else if (voterId && hasVoted) {
        res
          .status(401)
          .json({ message: 'Sorry, you have already participated in poll' });
      } else {
        const choice = await poll.choices.id(choiceId);
        const votedChoice = { name, votes: choice.votes + 1 };

        await choice.set(votedChoice);
        await poll.votedBy.push(voterId);

        poll.save();

        res
          .status(200)
          .json({
            message: 'Thank you for voting.',
            poll,
          });
      }
    } catch (error) {
      res.status(404).json({ error });
    }
  }

  // ...
}

export default PollsController

投票界面

interface Poll {
  title: string;
  category: string;
  addedBy: string;
  votedBy?: [string];
}

export default Poll;

轮询模式

import * as mongoose from 'mongoose';

import PollInterface from './poll.interface';

const Schema = mongoose.Schema;

const ChoiceSchema = new Schema({
  name: { type: String },
  votes: { type: Number }
});

const PollSchema = new Schema({
  title: { type: String },
  category: { type: String },
  choices: [ChoiceSchema],
  addedBy: { type: Schema.Types.ObjectId, ref: 'User' },
  votedBy: [{ type: Schema.Types.ObjectId, ref: 'User' }]
},{
    timestamps: true,
});

const Poll = mongoose.model<PollInterface & mongoose.Document>('Poll', PollSchema);

export default Poll;

编辑:同时包含投票界面和架构代码段

2 个答案:

答案 0 :(得分:0)

“字符串”类型不存在属性“等于”:如果它在JS中有效,则表示投票者不是您声明的“字符串”。

检查方法Poll.findById(pollId)的签名。

答案 1 :(得分:0)

对于第一个错误,您的接口将votedBy定义为字符串数组。您可以在数组上调用.some,然后在不是类型.equals的方法的字符串上调用string。您可以更改

const hasVoted = poll.votedBy.some((voter): boolean => voter.equals(voterId));

const hasVoted = poll.votedBy.some((voter): boolean => voter === voterId);

第二个,您没有在choices界面上定义Poll。因此,下一行因为它而使打字稿编译器失败。

const choice = await poll.choices.id(choiceId);

您需要在choices界面上添加Poll作为属性。我不确切知道您的实现是什么,但是您想在Poll接口中添加如下所示的内容。

choices: {
  id:() => string;
}

从您的代码看来,您似乎正在尝试从给定的choice中找到匹配的choiceId