1

how to clone object by type in typescript? i try Object assign, deconstructing, spreading, etc...

type A = {a: string} // not only 'a', more complex
type B = {b: string} // not only 'b', more complex
type C = A & B

const c = {a: 'a', b: 'b'} // not only 'a' and 'b', more complex

/** try **/
// Object.assign({}, c as A)
// copyA = {a: 'a', b: 'b'}

/** how to copy type-safe? like this. **/
// copyA = customCopy<A>(c);
// copyA = {a: 'a'}
  • Does this code only need to copy `A`s? Or are you hoping to somehow have it copy any possible type? – Nicholas Tower Dec 25 '21 at 02:58
  • @NicholasTower the latter – Jinyong Kim Dec 25 '21 at 03:16
  • 3
    How would you write that code in plain javascript? The types only exist at compile time, so typescript can *describe* what your code is doing, but it can't give it any new capabilities. The only things i can think of that would kinda match what you're describing is a function where you pass in an object and an array of string keys you want to copy, and then the function copies those properties onto a new object. – Nicholas Tower Dec 25 '21 at 03:21

0 Answers0