【问题标题】:TypeScript: Using Type Parameters in Generic ConstraintsTypeScript:在通用约束中使用类型参数
【发布时间】:2017-05-19 13:33:56
【问题描述】:

Using Type Parameters in Generic Constraints”在 TypeScript 站点中显示了下面的示例代码。但是出现了以下错误:

'Type 'U[keyof U]' 不能分配给 type 'T[keyof U]'。输入“U” 不能分配给类型“T”。'

function copyFields<T extends U, U>(target: T, source: U): T {
    for (let id in source) {
        target[id] = source[id];
    }
    return target;
}
let x = { a: 1, b: 2, c: 3, d: 4 };
copyFields(x, { b: 10, d: 20 });

事实上,这不会在 Playground 中运行。代码有什么问题?

【问题讨论】:

标签: javascript typescript


【解决方案1】:

U 不能分配给 T 是有道理的,因为满足 U 的对象可能具有 T 没有的其他字段:

interface Foo { foo: number; }
interface Bar extends Foo { bar: number; }
interface Bar2 extends Foo { bar: string; }

function assign<T extends U, U>(b: U): T {
    const returnVal: T = b;  // error: Type 'U' is not assignable to type 'T'.
    return returnVal;
}

const bar2: Bar2 = { foo: 7, bar: "happy" };
assign<Bar, Foo>(bar2);

因此,由于U 不能分配给T,我们无法保证特定的U[keyof U] 可以分配给T[keyof U]

(我对这个解释不是 100% 有信心,但对我来说似乎很有意义。)


但是,通过修改您输入内容的方式,您可以编写一个按预期工作的copyFields 版本like this

function copyFields<T, K extends keyof T>(target: T, source: Pick<T, K>) {
    for (let id in source) {
        target[id] = source[id];
    }
    return target;
}

【讨论】:

  • 非常感谢您的回答。我明白你的解释。修改后的代码运行良好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 2020-02-28
  • 2020-06-07
  • 1970-01-01
  • 2021-11-01
  • 2020-01-15
  • 2019-06-27
相关资源
最近更新 更多