【问题标题】:Why can't I assign a U to a Partial<T> when T extends U? [duplicate]当 T 扩展 U 时,为什么我不能将 U 分配给 Partial<T>? [复制]
【发布时间】:2020-05-25 17:31:43
【问题描述】:

例如:

interface U {
  u: boolean;
}

const f = <T extends U>() => {
  const t: Partial<T> = {u: true};
};

我收到以下错误:

Type '{ u: true; }' is not assignable to type 'Partial<T>'.ts(2322)

Playground link

有没有办法在不强制转换的情况下解决这个问题?

【问题讨论】:

  • 从技术上讲,“有没有办法在不强制转换的情况下解决这个问题?” 是“是的:const t: Partial&lt;T&gt; = {u: true} as Partial&lt;T&gt;;”但这并没有真正的帮助...... ;-) 将其改写为 "...不使用类型断言是否准确?"
  • 这工作const t = { u: true } as Partial&lt;T&gt;;

标签: typescript typescript-generics


【解决方案1】:

TypeScript 抱怨的问题如下:

Type '{ u: true; }' is not assignable to type 'Partial&lt;T&gt;'.ts(2322)

你的函数f可以被调用:

f<{ u: boolean, v: boolean }>(); // ok since U is "implemented" but not "v"

这会打开一个选项,即您在函数 { u: true } 中提供的对象的通用实现和提供的具体实现可能会有所不同。

TypeScript 编译器不会强制您定义与它扩展相同的类型,只要完全提供 U,您仍然可以指定更具体的 U 实现(在本例中为布尔标志 u) .

一些可能的解决方案是:

使用类型转换(如前所述):

interface U {
  u: boolean;
}

const f = <T extends U>() => {
  const t: Partial<T> = {u: true} as Partial<T>;
};

f<U>();

缺点:{ u: true } 很可能被替换为:{ v: true },这可能会导致您稍后在代码中出现 undefined 问题。

尝试重新表述你的功能

要告诉编译器准确使用U 类型,如果可能,您可以尝试重新定义函数并将常量t 作为函数参数移动。

interface U {
  u: boolean;
}

const f = <T>(u: T) => {
  const t: Partial<T> = u;
};

f<{ u: boolean }>({ u: true });

考虑泛型是否相关

您的函数需要一个泛型类型,但您的函数体分配了一个具体类型,这会导致这里出现问题。您可以考虑泛型是否相关。一个通用的免费替代方案是:

interface U {
  u: boolean;
}

const f = () => {
  const t: Partial<U> = {u: true};
};

f();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 2021-11-16
    • 2020-12-06
    相关资源
    最近更新 更多