首页 > 解决方案 > 将新值更新到现有接口打字稿

问题描述

 const localBook = await getBook(bookId);

  const bookRemote: IBook = {
    business_name: bookName,
    business_image: businessImage,
    business_owner_name: businessOwnerName,
    updated_at: String(getCurrentTime()),
    updated_by_user: user.user_id,
    updated_by_device: deviceInfo.device_id,
    book_name: bookName,
  };

  const book = {
    ...localBook,
    bookRemote,
  };

  try {
    // add in local DB
    await updateBookDB(book);
  } catch (e) {
    // catch local DB error and reject current promise
    return Promise.reject(e);
  }

我想在接口打字稿中更新我的属性值,但是它给出了缺少属性的错误。虽然我在这里附加了 localBook。

在此处输入图像描述

我的问题:

localBook 包含所有接口属性和值,我需要为通过 bookRemote 对象传递的属性添加新属性和值,我该如何实现?

标签: typescriptinterface

解决方案


我猜这是你需要的东西:

const bookRemote = {
  business_name: bookName,
  business_image: businessImage,
  business_owner_name: businessOwnerName,
  updated_at: String(getCurrentTime()),
  updated_by_user: user.user_id,
  updated_by_device: deviceInfo.device_id,
  book_name: bookName,
} as IBookValue; // you can take advantage by using IBookValue which requires in your `updateBookDB` method too

const book = {
  ...localBook,
  ...bookRemote, // spread your object
};


推荐阅读