简体   繁体   English

类型“未知”不可分配给类型“从不”.ts(2322)

[英]Type 'unknown' is not assignable to type 'never'.ts(2322)

If you want to run this in the browser, I create a Typescript Playground如果你想在浏览器中运行它,我创建了一个Typescript 游乐场

I had similar errors before which I was able to fix, but this one just does not seem to want to go away.我有过类似的错误,之前我能够修复,但这个错误似乎不想 go 消失。 I am sure it's a typing problem, but no clue on how to go about this.我确定这是一个打字问题,但不知道如何解决这个问题 go。

I looked up similar situations which all advocated you'd properly type the object you're working on, which'd be task in my case, which I casted to be of type TaskInterface.我查找了类似的情况,所有这些情况都主张您正确键入您正在处理的 object,在我的情况下,这将是task ,我将其转换为 TaskInterface 类型。 I typed the param of replace.key as keyof TaskInterface.我将 replace.key 的参数键入为 keyof TaskInterface。 Not sure what more I can do.不知道我还能做什么。

Can the optional properties in the interface be the cause of it saying typeof never?接口中的可选属性是否会导致它说 typeof never?

interfaces接口

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>;
}

Function Function

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: changed replace param to this编辑:将替换参数更改为此

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
}

now it's throwing the following error: Type 'unknown' cannot be used as an index type.ts(2538)现在它抛出以下错误: Type 'unknown' cannot be used as an index type.ts(2538)

unknown is just like any , but inferred its type when type checking. unknownany一样,但在类型检查时推断其类型。 So unknown must not be assigned as a value of TaskInterface .所以unknown不能被分配为TaskInterface的值。 Then, need to type value like following:然后,需要键入如下value

async function edit<K extends keyof TaskInterface>(
    query: {
      key: keyof TaskBase;
      value: TaskBaseInterface[K];
    },
    replace: { key: keyof TaskBase; value: TaskBaseInterface[K] }
  ): Promise<TaskInterface | void> {
    const { key, value } = query;
   ...

It's not necessary to use generics, though I use to make the code easy to read.没有必要使用 generics,尽管我使用它是为了使代码易于阅读。

Extending on Akihito's answer, this could work for you:扩展明仁的回答,这可能对你有用:

async function edit<K extends keyof TaskInterface>(
  query: { key: keyof TaskBase; value: unknown; },
  replace: { key: K; value: TaskInterface[K]; }
): Promise<TaskInterface | void> {
  // ...
}

This way you would make sure replace object's key and value refer to the same property, so the error should disappear.这样您就可以确保替换对象的keyvalue引用相同的属性,因此错误应该消失。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TS2322:类型“BillingSummaryDTO[]”不可分配给类型“从不” - TS2322: Type 'BillingSummaryDTO[]' is not assignable to type 'never' 类型“元素”不可分配给类型“字符串”.ts(2322) - Type 'Element' is not assignable to type 'string'.ts(2322) 类型 &#39;undefined&#39; 不能分配给类型 &#39;number&#39; .ts(2322) - Type 'undefined' is not assignable to type 'number' .ts(2322) 类型“编号”不可分配给类型“PersonConfig”。 ts(2322) - Type 'number' is not assignable to type 'PersonConfig'. ts(2322) 类型 'HTMLButtonElement' 不可分配给类型 'string'.ts(2322) - Type 'HTMLButtonElement' is not assignable to type 'string'.ts(2322) 类型 &#39;string&#39; 不可分配给类型 &#39;(url: string) =&gt; string&#39;.ts(2322) - Type 'string' is not assignable to type '(url: string) => string'.ts(2322) 类型“IntersectionObserver”不可分配给类型“null”。 TS2322 [React,intersectionObserver] - Type 'IntersectionObserver' is not assignable to type 'null'. TS2322 [React, intersectionObserver] 类型“可观察” <boolean | “”> &#39;不可分配给&#39;Observable类型 <boolean> &#39;TS2322 - Type 'Observable<boolean | “”>' is not assignable to type 'Observable<boolean>' TS2322 “Firebase”类型不能分配给“null”类型。 TS2322 - Type 'Firebase' is not assignable to type 'null'. TS2322 类型 &#39;(activeTabIndex: number) =&gt; void&#39; 不可分配给类型 &#39;() =&gt; number&#39;.ts(2322) - Type '(activeTabIndex: number) => void' is not assignable to type '() => number'.ts(2322)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM