【问题标题】:Infer type of sibling properties based on another siblings' type根据另一个兄弟姐妹的类型推断兄弟属性的类型
【发布时间】:2021-02-25 18:47:09
【问题描述】:

我正在尝试构建一个简单的抽象来列出对象的补丁。

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,
    },
  ],
};

我希望根据给定的key 输入oldValuenewValue。 不幸的是,正如代码 cmets 中所述,它不起作用。

感谢您的任何建议!

【问题讨论】:

    标签: typescript types type-inference


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 2021-01-30
      • 1970-01-01
      相关资源
      最近更新 更多