我尝试在Vue JS中映射来自API的数组响应,但在执行此操作时遇到了typescript错误。下面是我的代码:
methods: {
export interface WebspaceBackupArtifact {
readonly date?: string;
readonly name?: string | null;
readonly path?: string | null;
readonly type?: string | null;
}
interface WebspaceBackupArtifactExtended extends WebspaceBackupArtifact {
size?: number;
type?: string;
}
let artifacts = [] as WebspaceBackupArtifactExtended[];
if (response?.data?.artifacts) {
artifacts = response.data.artifacts
.map((artifact: WebspaceBackupArtifactExtended) => ({
...artifact,
date: moment(artifact.date!).format('DD-MMM-YYYY'),
}))
.sort(
(
a: WebspaceBackupArtifactExtended,
b: WebspaceBackupArtifactExtended,
) => a.type!.localeCompare(b.type!),
);
}
}
生成以下错误:
ERROR in /app/src/views/BackupAndRestore/BackupAndRestoreWebspaceBackup.vue(594,16):
my-project | 594:16 Argument of type '(artifact: WebspaceBackupArtifactExtended) => { date: string; size?: number | undefined; type?: string | undefined; name?: string | null | undefined; path?: string | null | undefined; }' is not assignable to parameter of type '(value: WebspaceBackupArtifact, index: number, array: WebspaceBackupArtifact[]) => { date: string; size?: number | undefined; type?: string | undefined; name?: string | ... 1 more ... | undefined; path?: string | ... 1 more ... | undefined; }'.
my-project | Types of parameters 'artifact' and 'value' are incompatible.
my-project | Type 'WebspaceBackupArtifact' is not assignable to type 'WebspaceBackupArtifactExtended'.
my-project | Types of property 'type' are incompatible.
my-project | Type 'string | null | undefined' is not assignable to type 'string | undefined'.
my-project | Type 'null' is not assignable to type 'string | undefined'.
my-project | 592 | if (response?.data?.artifacts) {
my-project | 593 | artifacts = response.data.artifacts
my-project | > 594 | .map((artifact: WebspaceBackupArtifactExtended) => ({
my-project | | ^
my-project | 595 | ...artifact,
my-project | 596 | date: moment(artifact.date!).format('DD-MMM-YYYY'),
my-project | 597 | }))
我曾尝试查看其他类似的问题,这些问题有类似的错误信息,但在这种情况下无法提取任何对我有帮助的有价值的信息,因此我不确定我做错了什么。
我是不是扩展接口错了?
发布于 2021-02-02 08:59:23
错误消息是您有一个回调,它需要一个WebspaceBackupArtifactExtended
,但您的response.data.artifacts
数组是一个array
of WebspaceBackupArtifact
。
扩展版本可以分配给基本版本,但反之亦然。具体原因是type
属性。WebspaceBackupArtifact
允许string | null
,而WebspaceBackupArtifactExtended
只允许string
。
在您提供的代码中,response.data.artifacts
没有指定类型,但根据错误消息,我可以断定它是WebspaceBackupArtifact[] | undefined
。您可以做的一件事是删除map
和sort
回调中的WebspaceBackupArtifactExtended
注释,让它从数组类型中推断出来。
您可能还想考虑如何更好地处理未定义.date
和.type
的实例,而不是断言将定义它们。
https://stackoverflow.com/questions/66000962
复制相似问题