首页 > 解决方案 > 输入'recordedVideoLibraryEntry | null' 不可分配给类型 'recordedVideoLibraryEntry'

问题描述

这是界面

    export interface recordedVideoLibraryEntry {
  recordingId: string;
  name: string;
  description: string;
  timestamp: string;
  video: any;
}

我尝试从 localStorage 获取价值并分配给recordedVideoLibraryEntry

export const updateRecordingDetails = async (data) => {
  const {
    recordingId,
    name,
    description,
    timestamp,
    video,
  }: recordedVideoLibraryEntry = await library.getItem(data.recordingId);

  const entry: recordedVideoLibraryEntry = {
    recordingId,
    name: data.name || name,
    timestamp,
    description: data.description || description,
    video,
  };

  await library.setItem(recordingId, entry);
};

然后我收到以下错误

    Type 'recordedVideoLibraryEntry | null' is not assignable to type 'recordedVideoLibraryEntry'.
  Type 'null' is not assignable to type 'recordedVideoLibraryEntry'.ts(2322)

标签: typescript

解决方案


null@TJ Crowder 是正确的,您需要检查library.getItem.

(旁注:Typescript 实际上说WindowLocalStorage['localStorage']['getItem']只能返回stringor null,但我不知道这是否准确。它是返回你的对象,还是你是 JSON 编码/解码它?)

在我们这样做的同时,我们还要删除一些不必要的解构和重组,因为我们只更改了两个属性。

我们还要求它data有一个recordingId,因为没有它我们就不能调用getItemname并且description似乎是可选的。如果这些可以具有类似的值,则您的类型定义应该更改null。我假设它们要么存在且有效,要么完全不存在。

仅供参考,这不是必需的,但它是类型和接口使用大写名称的约定。

export const updateRecordingDetails = async (
    data: Pick<RecordedVideoLibraryEntry, 'recordingId'> & Partial<RecordedVideoLibraryEntry>
): Promise<void> => {

    const foundEntry = await library.getItem(data.recordingId);

    if (foundEntry === null) {
        // return an error?
    }

    else {
        // now know that it is not null

        // copy all properties of foundEntry, then override two
        const entry: RecordedVideoLibraryEntry = {
            ...foundEntry,
            name: data.name || foundEntry.name,
            description: data.description || foundEntry.description,
        };

        // note: data.recordingId and foundEntry.recordingId should be the same, 
        // but I'm not sure which you want to use here in the rare case of a mismatch error.
        // you could even throw an error on mismatch and not update either
        await library.setItem(foundEntry.recordingId, entry);
    }
};

打字稿游乐场链接


推荐阅读