A function that accepts any type and subtype

I want to write the following function

function override<T, U>(first: T, second: U): T { let result = <T>{}; for (let id in first) { result[id] = first[id]; } for (let id in second) { result[id] = second[id]; } return result; } 

but make it typical. In my case, using T and U are simple record types. I want T to be required to have all the properties of U Is there any way to express this attitude?

+3
source share
2 answers

You cannot do this in a single function declaration. The reason is that extends generic constrain cannot reference other generics in the same group. However, you can divide the function into two parts (currying). Then use the type of the first argument (now in a separate function) to restrict the type of the second argument, as shown below:

 var override = <T>(first:T) => <U extends T>(second:U) : T => { let result = <T>{}; for (let id in first) { result[id] = first[id]; } for (let id in second) { result[id] = second[id]; } return result; } override({a:123})({a:123, b:456}); // okay override({a:123})({b:456}); // error 
+4
source

I know his old question, but TS currently supports the following syntax:

type Partial<T> = { [P in keyof T]?: T[P]; }

(which is in lib.d.ts, so you don't need to include it in your code)

So:

function override<T>(first: T, second: Partial<T>): T { ...

0
source

All Articles