TypeScript: using type parameters in general constraints

Using Type Parameters in General Constraints ” on the TypeScript site shows the sample code below. But the following error occurred:

'Type' U [keyof U] 'cannot be assigned to type' T [keyof U] '. Type 'U' is not assigned 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 work on the playground. What is wrong with the code?

+4
source share
1 answer

It makes sense that it is Unot assigned T, since an object that satisfies Ucan have additional fields that it Tdoes not have:

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;
}
+3

Source: https://habr.com/ru/post/1665822/


All Articles