【问题标题】:Infer the type of property on interface parametrically given a specifc key of that interface给定接口的特定键,以参数方式推断接口上的属性类型
【发布时间】:2020-10-24 03:39:06
【问题描述】:

给定一个异构接口,我想生成一个类型安全的函数,该函数对该接口的给定属性进行操作。例如,像这样:

interface State {
  a: boolean;
  b: string;
  c: number;
}

// "enclose" the Interface type variable <I> so that I can generate several functions that
// operate on different properties of <I>
function createGenerator<I>() { 
  return function createOperationForProperty<K extends keyof I>(propertyName: K) {
    return function operation<T>(t: T): T {
      return calculationWith(t);
    }
  }
}

返回的函数“createOperationForProperty”被限制为K extends keyof I,因此我只能将I 上的键作为propertyName 传递。但是T 不受约束。我希望它是I[propertyName] 的类型。 I[keyof I] 类型只会将其限制为I 中的任何类型,而我希望它只接受与“propertyName”对应的特定类型。

为了完成这个例子,你可以这样应用它:

const createOperation = createGenerator<State>();
const operationOnA = createOperation("a");

dispatch(operationOnA("wrongType")); 

希望最后一行不会通过类型检查,因为State.aboolean

【问题讨论】:

    标签: typescript generics higher-order-functions


    【解决方案1】:

    您可以在operation 中要求T extends I[K],以确保参数的类型与对象上的属性值的类型相匹配:

    return function operation<T extends I[K]>(t: T): T {
    

    【讨论】:

    • 这似乎可行,谢谢!但是,我现在收到返回函数的错误:expected call-signature,并且我为这些编写 typedef 的努力遇到了需要在提供类型之前声明类型的问题。例如,createOperatonForProperty 的 typedef 可能需要引用 T,但无法找到 T
    • 如果你还需要createOperationForProperty 来知道值的类型,你可以在那里定义它:return function createOperationForProperty&lt;K extends keyof I, T extends I[K]&gt;(propertyName: K) {
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 2014-05-20
    • 2020-02-28
    相关资源
    最近更新 更多