【发布时间】:2020-12-27 16:37:09
【问题描述】:
如果你想在浏览器中运行它,我创建一个Typescript Playground
我有类似的错误之前我能够修复,但这个错误似乎并不想消失。我确定这是一个打字问题,但不知道如何解决这个问题。
我查找了类似的情况,所有这些情况都建议您正确键入您正在处理的对象,在我的情况下是 task,我将其转换为 TaskInterface 类型。我将 replace.key 的参数输入为 keyof TaskInterface。不知道我还能做什么。
接口中的可选属性会不会是导致 typeof never 的原因?
接口
export interface PopulatableTaskInterface {
columns?: unknown;
}
export interface TaskBase extends PopulatableTaskInterface {
title: string;
description?: string;
participants?: Array<string>;
deadline?: Date;
taskIdentifier?: number;
messageIds?: Types.Map<string>;
guildId: mongoose.Types.ObjectId;
completed?: boolean;
createdTimestamp?: number;
completedTimestamp?: number;
wip?: boolean;
}
export interface TaskBaseInterface extends TaskBase, mongoose.Document {}
export interface TaskInterface extends TaskBaseInterface {
columns: Types.Array<Schema.Types.ObjectId>;
}
功能
async edit(
query: {
key: keyof TaskBase;
value: unknown;
},
replace: { key: keyof TaskInterface; value: unknown }
): Promise<TaskInterface> {
const { key, value } = query;
try {
const task = (await TaskModel.findOne({ [key]: value })) as TaskInterface;
if (!task) {
throwError(
`Insufficient query: ${query}`,
Errors.insufficientQuery,
__dirname,
__filename
);
}
task[replace.key] = replace.value; // This is where I get the error
task.markModified(replace.key);
task.save();
return task;
} catch (err) {
console.log(err);
}
}
}
编辑:将替换参数更改为此
edit(query:{...}, replace: {key: keyof TaskBase, value: unknown}):
Promise<TaskInterface> {
// code here
task[replace.key] = replace.value; // replaced replace.key for each key key manually
// by doing `task["taskIdentifier"] = replace.value`, etc.
// which DID NOT throw an error
}
现在它抛出以下错误:
Type 'unknown' cannot be used as an index type.ts(2538)
【问题讨论】:
标签: javascript typescript types