简体   繁体   中英

Typescript create Object copy with all key properties but different type

I have a question regarding the types I need to use to obtain the following:

type keys = "foo" | "bar";

type Type1 = Record<keys, number>;
// Using `keyof Type1` just in case :)
type Type2 = Record<keyof Type1, boolean>;

// Created somewhere, we just have this
const foo: Type1 = {
  foo: 0,
  bar: 3
};

// How do I create a `Type2` object without manually specifying all the props?
// Given that I have all the needed keys in foo?
const bar: Type2 = ???

I have already tried with a couple of times with Object.assign and object spread without any result nice.

// `number` not assignable to boolean
const bar: Type2 = { ...foo }; // not working
const bar: Type2 = Object.assign({}, foo); // not working
// Not working as expected, type is `Type1 & Type2`
const bar = Object.assign({} as Type2, foo); // not working
// Working but a bit ugly no?
const bar: Type2 = Object.assign({} as Type2, foo); // Working

The implementation should be inside a function that maps from Type1 to Type2 like:

const foonction = (obj: Type1): Type2 => {
  // create object and map values
}

Type2 is already has the same keys as Type1 so all you have to do is to map properties, which are part of objects and not types. So your foonction may look like this

const foonction = (obj: Type1): Type2 => {
    let res = <Type2>{}; 
    Object.keys(obj).forEach(key => res[key as keyof Type2] = obj[key as keyof Type1] != 0);  // Do your mapping here
    return res;
}

Object.assign will produce result of type Type1 & Type2 ( intersection type ). So you'll not do mapping, you'll have object bar containing the same properties of the same type as foo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM