输入'recordedVideoLibraryEntry | “ null”不可分配给“ recordedVideoLibraryEntry”类型

时间:2020-10-19 15:51:24

标签: typescript

这是界面

    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)

1 个答案:

答案 0 :(得分:2)

@ T.J。 Crowder是正确的,您需要检查null返回的可能的library.getItem值。

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

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

我们还要求data有一个recordingId,因为没有它我们就不能打电话给getItemnamedescription似乎是可选的。如果这些类型的值可以具有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);
    }
};

Typescript Playground Link