[英]TypeScript: Using Type Parameters in Generic Constraints
TypeScript站點中的“ 在通用約束中使用類型參數 ”顯示下面的示例代碼。 但發生以下錯誤:
'類型'U [keyof U]'不能分配給'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中運行。 代碼有什么問題?
因為滿足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
版本, 如下所示 :
function copyFields<T, K extends keyof T>(target: T, source: Pick<T, K>) {
for (let id in source) {
target[id] = source[id];
}
return target;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.