TypeScript-Handbook icon indicating copy to clipboard operation
TypeScript-Handbook copied to clipboard

The example code in "Generic" does not run

Open FumioNonaka opened this issue 8 years ago • 4 comments

The example code of "Using Type Parameters in Generic Constraints" in "Generic" does not run. The following error is shown.

'Type 'U[keyof U]' is not assignable to type 'T[keyof U]'. Type 'U' is not assignable to type '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 });

In fact, this does not run in the Playground.

FumioNonaka avatar Jan 05 '17 07:01 FumioNonaka

This example is not correct now. It should be typed as:

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

mhegazy avatar Jan 05 '17 23:01 mhegazy

A PR would be welcomed.

mhegazy avatar Jan 05 '17 23:01 mhegazy

Hey I am newbie will love to submit a PR

Swap76 avatar Oct 03 '19 17:10 Swap76

This issue seems fixed by https://github.com/microsoft/TypeScript-Handbook/pull/489

sasurau4 avatar Oct 22 '19 18:10 sasurau4