【问题标题】:Infer type of a parameter from another从另一个推断参数的类型
【发布时间】:2022-10-24 01:11:19
【问题描述】:

给定常量对象实现接口

interface Example {
  item1?: {
    item1?: string,
    item2?: string,
  },
  item2?: {
    item1?: string,
    item2?: string,
  }
}

const exampleObject: Example = {
  item1: {
    item1: 'test'
  }
};

如何构造一个函数,该函数将接受此对象作为第一个参数,第二个参数将具有基于传递的对象的类型,而不是对象的接口?

function exampleFunction<T>(a: T, b: ??) { // <- how to define second parameter?

}

// correct - type exactly the same as first object
exampleFunction(exampleObject, {
  item1: {
    item1: 'test'
  }
});

// incorrect - type not the same as the first object
exampleFunction(exampleObject, {
  item1: {
    item1: 'test',
    item2: 'test'
  }
});
// incorrect - type not the same as the first object
exampleFunction(exampleObject, {
  item2: {}
});
// etc...

【问题讨论】:

  • 您需要从 exampleObject 中删除类型注释才能使其正常工作。
  • 这现在是难以置信的明显。谢谢
  • 这种方法的问题是我在 exampleObject 上失去了自动完成功能。所以问题实际上是,如何获得从实现 Example 接口的 exampleObject 派生的类型,但没有未指定的键,其中 Example 接口的所有键都是可选的。这是否可能,或者是否必须动态检查密钥是否匹配?

标签: typescript typescript-generics


【解决方案1】:

我想你正在寻找这样的东西:

const exampleFunction = <T1 extends Example, T2 extends T1>(obj1: T1, obj2: T2) => {
  //do stuff
}

这样,您为第一个参数传入的任何对象都会设置您对第二个参数所需的最低要求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2020-03-11
    相关资源
    最近更新 更多