У меня есть вопрос относительно типов, которые мне нужно использовать для получения следующего:
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 = ???
Я уже пробовал пару раз с Object.assign
и объект распространялся без какого-либо результата.
// `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
Реализация должна быть внутри функции, которая отображается от Type1
до Type2
, например:
const foonction = (obj: Type1): Type2 => {
// create object and map values
}