从接口泛型中键入推断

时间:2018-06-11 14:27:23

标签: typescript generics type-inference

我有一个接口,它接受两个显式的通用参数:

interface ConnectedComponent<TSelectors, TActions> {
  selectors: TSelectors;
  actions: TActions;
  (props: SelectorProps<TSelectors> & ActionProps<TActions>): any;
}

以下是我使用它的方式:

let selectors = { ... };
let actions = { ... };

let Counter: ConnectedComponent<typeof selectors, typeof actions> = props => { ... };
Counter.selectors = selectors;
Counter.actions = actions;

我更喜欢做的是从指定的属性中推断出泛型:

let Counter: ConnectedComponent = { ... };
Counter.selectors = { ... };
Counter.actions = { ... };

但是我不知道如何在界面中捕获typeof Counter.selectorstypeof Counter.actions

1 个答案:

答案 0 :(得分:6)

执行此操作的唯一方法是使用额外的函数并利用函数的推理行为。为了推断函数的参数,我们需要使用一个返回函数方法的函数:

interface ConnectedComponent<TSelectors, TActions> {
    selectors: TSelectors;
    actions: TActions;
    (props: SelectorProps<TSelectors> & ActionProps<TActions>): any;
}

function createConnectedComponent<TSelectors, TActions>(props: { selectors: TSelectors; actions: TActions; }): (fn: (props: SelectorProps<TSelectors> & ActionProps<TActions>) => any) => ConnectedComponent<TSelectors, TActions> {
    return fn => Object.assign(fn, props);
}
let Counter2 = createConnectedComponent({
    selectors: {
        // ...
    },
    actions: {
        // ...
    }
})(p => { /*...*/ }); //p is TSelectors & TActions as expected