属性“insertId”在类型“Boolean |”上不存在 (Partial<TEvents> & { insertId?: 数字 | 未定义; })'

ami*_*neh 1 javascript node.js typescript

我有一段 JavaScript 代码,我正在尝试将其转换为 TypeScript

route.delete('/:id', async (req, res) => {
    try {
        const result = await events.delete(req.params.id);
        res.send({ success: true, data: { id: result.insertId } });
Run Code Online (Sandbox Code Playgroud)

这段代码过去在 js 中工作得很好,但现在我已将其转换为打字稿,我在 insertId 上收到此错误

Property 'insertId' does not exist on type 'Boolean | (Partial<TEvents> & { insertId?: number | undefined; })'. Property 'insertId' does not exist on type 'Boolean'.ts(2339)

我尝试通过在 TEvents 类型上添加 insertId 来解决问题,但它不起作用

这是我的事件模型:

import { Model } from './Model';
type TEvents = {
    total    ?:string;
    insertId ?:any;
    status   ?:any;
    id       ?:any;
}
export class Events extends Model<TEvents> {

    constructor() {
        super('events');
    }

}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激

T.J*_*der 5

问题是deletePromise 的实现值是联合类型。它要么是 a Boolean,要么是 a Partial<TEvents> & { insertId?: number | undefined; }insertId仅存在于该联合的一部分上,因此为了安全地使用它,您必须检查您得到了什么, aBoolean或 a Partial<TEvents> & { insertId?: number | undefined; }

您可以使用类型保护来做到这一点,例如:

route.delete('/:id', async (req, res) => {
    try {
        const result = await events.delete(req.params.id);
        if ("insertId" in result) {
            res.send({ success: true, data: { id: result.insertId } });
        } else {
            // What you got either was a boolean or was a `Partial<TEvents>`
            // without an `insertId` property
        }
Run Code Online (Sandbox Code Playgroud)

旁注:使用Boolean(而不是boolean小写的 )作为类型很奇怪,因此可能值得查看 的定义events.delete并看看您是否真的打算使用Boolean而不是boolean。更多内容请参阅文档