1

There are some way to define such interface for merge function:

interface mergeFunc<T, S, P exntends T,S>(t:T, s:S):P;

var merge:mergeFunc = function (t:any, s:any):any {
   var res = {};
   for (let x in t) res[x] = t[x];
   for (let x in s) res[x] = s[x];
   return res;
}

?

2 Answers 2

2

In TypeScript 1.6 (or TypeScript nightly today, use npm install typescript@next), you'll be able to use intersection types to write this:

declare function mergeFunc<T, S>(t:T, s:S): T & S;

See https://github.com/Microsoft/TypeScript/pull/3622

Sign up to request clarification or add additional context in comments.

Comments

0

For immutable change of T

If you only need to merge properties compatible with the initial type, since TypeScript 1.8 you can use type parameters as constraints :

const merge = function<T extends S, S>
( t: T, s: S ) : T {
  const res: any = {}
  // copy
  for ( const k in t ) {
    if ( t.hasOwnProperty ( k ) ) {
      res [ k ] = t [ k ]
    }
  }
  // merge
  for ( const k in s ) {
    if ( s.hasOwnProperty ( k ) ) {
      res [ k ] = s [ k ]
    }
  }
  return res
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.