说我有
interface User {
name: string;
age: number;
}
interface Car {
year: number;
model: string;
}
interface Action<T> {
assign<K extends keyof T>(key: K, value: T[K]): void;
}
这允许我这样做:
const userActions: Action<User> = ...;
const carActions: Action<Car> = ...;
userActions.assign('age', 1); // all good
userActions.assign('foo', 2); // error that `foo` does not exist
userActions.assign('age', 'foo'); // error that type string is not assignable to age
carActions.assign(...); // same behavior for car
现在我想创建可以传递给assign
的辅助方法,例如:
const logAndAssign = (key, value): void;
我希望能够做到
userActions.assign(logAndAssign('age', 1));
// etc
所以我想要这些辅助方法logAndAssign
来获取传递给它们的类型。我怎样才能做到这一点?
答案 0 :(得分:2)
您无法直接使用单个参数调用函数,您可以使用apply
但apply
调用不是类型安全的,调用logAndAssign
意味着您传递类型参数明确地说:
const logAndAssign = function <T, K extends keyof T>(key: K, value: T[K]): [K, T[K]] {
console.log(`${key} ${value}`);
return [key, value];
};
userActions.assign.apply(userActions, logAndAssign<User, 'age'>('age', 1));
更好的解决方案是替换assign
上的Action
函数,然后将其恢复:
function withLogging<T>(a: Action<T>, doStuff: (a: Action<T>) => void) {
let oldAssign = a.assign;
// Replace the assign function with a logging version that calls the original
a.assign = function <K extends keyof T>(key: K, value: T[K]): void {
console.log(`${key} ${value}`);
oldAssign.call(this, key, value);
};
try {
doStuff(a);
} finally {
//Restore the original assign
a.assign = oldAssign;
}
}
// Single call
withLogging(userActions, u => u.assign('age', 10));
// Multiple calls
withLogging(userActions, u => {
u.assign('age', 10);
u.assign("name", 'd');
});