代码之家  ›  专栏  ›  技术社区  ›  Nespony

打字的猫鼬?

  •  0
  • Nespony  · 技术社区  · 4 年前

    我有一个nodejs和typescript的项目。我正在使用mongoose连接mongoDb数据库。我的代码是这样的

    import { Schema, Document, Model } from 'mongoose';
    import * as mongoose from 'mongoose';
    
    export interface IProblem extends Document {
      problem: string;
      solution: string;
    }
    
    const ProblemSchema = new Schema({
      problem: { type: String, required: true },
      solution: { type: String, required: true },
    });
    
    export async function findOneByProblem(
      this: IProblemModel,
      { problem, solution }: { problem: string; solution: string }
    ): Promise<IProblem> {
      const record = await this.findOne({ problem, solution });
      return record;
    }
    
    export default mongoose.model('Problem', ProblemSchema);
    
    ProblemSchema.statics.findOneByProblem = findOneByProblem;
    
    export interface IProblemModel extends Model<IProblem> {
      findOneByProblem: (
        this: IProblemModel,
        { problem, solution }: { problem: string; solution: string }
      ) => Promise<IProblem>;
    }
    

    然而,在这些线路上

    const record = await this.findOne({ problem, solution });
    return record;
    

    我听到一个编译器错误这样说

    TS2322: Type 'IProblem | null' is not assignable to type 'IProblem'.   Type 'null' is not assignable to type 'IProblem'.
    

    1 回复  |  直到 4 年前
        1
  •  3
  •   AKX Bryan Oakley    4 年前

    你喜欢的类型 findOneByProblem IProblem

    正确的类型是

    Promise<IProblem | null>
    

    或者你可以从内部 if(problem === null) throw new Error("No Problem found"); 如果不想更改类型,可以在函数中使用类似的方法。