首页 > 解决方案 > 打字稿部分<>类型错误

问题描述

我的代码已经工作了,但现在它突然在 logEntry 上有一个类型错误:

Type '{ raw: string; timestamp: number; }' is not assignable to type 'Partial<ILogEntry>'.  

    Types of property 'constructor' are incompatible.
    Type 'Function' is missing the following properties from type 'Model<ILogEntry, {}>': base, 
    baseModelName, discriminators, modelName, and 59 more.(2322)

实现这一点的正确方法是什么?这是示例代码:

import { Schema, model, Model, Document } from "mongoose";
interface ILogEntry extends Document {
raw: string;
timestamp?: number;

}
const logEntry: Partial<ILogEntry> = {
            raw: "hey",
            timestamp: 213213,
        };

标签: typescript

解决方案


Looks like signature of the Document has been changed, if you don't plan to use constructor you can simply omit it, if it's acceptable of course.

const logEntry: Partial<Omit<ILogEntry, 'constructor'>> = {
  raw: "hey",
  timestamp: 213213,
};

and to avoid length to add a type for it

type PartialObj<T> = Partial<Omit<T, 'constructor'>>;

const logEntry: PartialObj<ILogEntry> = {
  raw: "hey",
  timestamp: 213213,
};

推荐阅读