简体   繁体   English

给定接口的特定键,以参数方式推断接口上的属性类型

[英]Infer the type of property on interface parametrically given a specifc key of that interface

Given an heterogeneous interface, I would like to generate a type-safe function that operates on a given property of that interface.给定一个异构接口,我想生成一个类型安全的 function,它对该接口的给定属性进行操作。 For example, something like this:例如,像这样:

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);
    }
  }
}

The returned function "createOperationForProperty" is constrained to K extends keyof I , so that I can only pass as propertyName a key that is on I .返回的 function "createOperationForProperty" 被限制为K extends keyof I ,因此我只能将I上的键作为propertyName传递。 But T is unconstrained.但是T是不受约束的。 I would like it to be the type of I[propertyName] .我希望它是I[propertyName]的类型。 The type I[keyof I] would only restrict it to any type in I , whereas I would like it to only accept the specific type corresponding to "propertyName".类型I[keyof I]只会将其限制为I中的任何类型,而我希望它只接受与“propertyName”对应的特定类型。

Just to finish the example, you could apply it like this:只是为了完成示例,您可以像这样应用它:

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

dispatch(operationOnA("wrongType")); 

The hope is that this last line would fail type checking, because State.a is a boolean .希望最后一行不会通过类型检查,因为State.aboolean

You can require that T extends I[K] in operation , to ensure that the type of the argument matches the type of the property value on the object:您可以要求 T 在operationT extends I[K] ,以确保参数类型与 object 上的属性值类型相匹配:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM