typescript - 输入'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)
解决方案
null
@TJ Crowder 是正确的,您需要检查library.getItem
.
(旁注:Typescript 实际上说WindowLocalStorage['localStorage']['getItem']
只能返回string
or null
,但我不知道这是否准确。它是返回你的对象,还是你是 JSON 编码/解码它?)
在我们这样做的同时,我们还要删除一些不必要的解构和重组,因为我们只更改了两个属性。
我们还要求它data
有一个recordingId
,因为没有它我们就不能调用getItem
。 name
并且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);
}
};
推荐阅读
- r - 防止 R shiny handsontable 重置为默认值
- c# - 反序列化 JSON 列表
- node.js - 与 Hasura 的 WebSocket 连接不适用于 Node.js 上的 ApolloClient v3
- c - 使用 SSE 向量化在 OpenMP 中将内部循环与残差计算并行化
- linux - 如何在 bash tar 命令中扩展变量
- python - wsgiref simple_服务器无法得到对请求的响应
- java - twitter4j 可以使用新的 Twitter API 吗?
- python - 使用 Django Check Framework 检测管理员未知字段?
- python - 多元 KDE Scipy Stats - 如果它不是高斯的怎么办?
- micronaut - #运行 Gralvm Micronaut 数据时出错