Вывод типа родственных свойств на основе типа другого родственного

#typescript #types #type-inference

#typescript #типы #вывод типа

Вопрос:

Я пытаюсь создать простую абстракцию, в которой перечислены исправления для объекта.

 type MyObject = {
  attributeA: string;
  attributeB: boolean;
  attributeC: number;
};
type MyObjectKeys = keyof MyObject;

type Difference<Key extends MyObjectKeys = MyObjectKeys> = {
  // The value of this attribute should determine
  // the type of the old and new value.
  key: Key;
  oldValue: MyObject[Key];
  newValue: MyObject[Key];
};

type Patch = {
  patches: Difference[];
};

const patch: Patch = {
  patches: [
    {
      key: 'attributeB',
      // Should be inferred as boolean.
      oldValue: '',
      // Both should have the same inferred type.
      newValue: 9,
    },
  ],
};
  

Я хочу oldValue , чтобы и newValue были напечатаны в соответствии с заданным key .
К сожалению, как указано в комментариях к коду, это не работает.

Я благодарен за любой совет!

Ответ №1:

Вывод типа не работает таким образом. Вам следует создать несколько помощников:

 type MyObject = {
  attributeA: string;
  attributeB: boolean;
  attributeC: number;
};
type MyObjectKeys = keyof MyObject;

type Difference<Key extends MyObjectKeys = MyObjectKeys> = {
  // The value of this attribute should determine
  // the type of the old and new value.
  key: Key;
  oldValue: MyObject[Key];
  newValue: MyObject[Key];
};

type Patch = {
  patches: Difference[];
};

function createPatch<T extends MyObjectKeys>(key: T, oldValue: MyObject[T], newValue: MyObject[T]): Difference<T> {
    return {
        key,
        oldValue,
        newValue,
    };
}

function addPatch<T extends MyObjectKeys>(key: T, oldValue: MyObject[T], newValue: MyObject[T], patch: Patch) {
    patch.patches.push(createPatch(key, oldValue, newValue));
}

const patch: Patch = {
  patches: [createPatch('attributeB', '', 9), createPatch('attributeA', '', 'newVal')],
};

addPatch('attributeC', 0, 10, patch);