【发布时间】: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.a 是boolean。
【问题讨论】:
标签: typescript generics higher-order-functions