Type ‘{ id: string; }’不能赋值给类型’DeepPartial<T>’

huangapple go评论54阅读模式
英文:

Type '{ id: string; }' is not assignable to type 'DeepPartial<T>'

问题

This error is occurring because TypeScript is not able to infer that the where property in your SearchOneOptions<T> interface should match the type DeepPartial<T>. To fix this error, you can explicitly specify the type parameter when calling the b function like this:

const b = <T extends { id: string }>(t: T) => {
  const a: SearchOneOptions<T> = {
    where: {
      id: t.id
    }
  }
}

This will ensure that TypeScript correctly infers the type of where as DeepPartial<T> based on the type of T that you provide when calling the b function.

Please note that I've just provided the translation of the code part, as you requested.

英文:

I have the following code trying to create a generic function to abstract my repository infra to create a where clausule.

export type DeepPartial&lt;T&gt; = T extends object
  ? {
    [P in keyof T]?: DeepPartial&lt;T[P]&gt;;
  }
  : T;

export interface SearchOneOptions&lt;ENTITY extends { id: string }&gt; {
  /** Names of object attributes nested in the result object that must be filled, if possible */
  includeNested?: string[];
  /** Entities that can be soft deleted won&#39;t appear in queries by default */
  withDeleted?: boolean;
  select?: string[];
  where?: DeepPartial&lt;ENTITY&gt;
}

const b = &lt;T extends { id: string }&gt;(t: T) =&gt; {
  const a: SearchOneOptions&lt;T&gt; = {
    where: {
      id: t.id
    }
  }
}

And I'm facing the following error
Type &#39;{ id: string; }&#39; is not assignable to type &#39;DeepPartial&lt;T&gt;&#39;.

Here is a playground to reproduce

Do you know how to solve this error? Thank you very much Type ‘{ id: string; }’不能赋值给类型’DeepPartial<T>’

答案1

得分: 1

`DeepPartial`中的条件类型不是必要的,因为在原始类型上的映射类型会导致原始类型值。

```ts
export type DeepPartial<T> = {
    [P in keyof T]?: DeepPartial<T[P]>;
};

Playground


<details>
<summary>英文:</summary>

The conditional type in `DeepPartial` is not necessary since a mapped type on a primitive results in the original primitive value.

```ts
export type DeepPartial&lt;T&gt; = {
    [P in keyof T]?: DeepPartial&lt;T[P]&gt;;
};

Playground

huangapple
  • 本文由 发表于 2023年5月25日 22:17:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333299.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定