时间:2018-01-17 02:18:17

标签: javascript typescript

说我有

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来获取传递给它们的类型。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

您无法直接使用单个参数调用函数,您可以使用applyapply调用不是类型安全的,调用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');
});