简体   繁体   English

键入 Vuex 方法风格的 Getter

[英]Typing a Vuex Method-Style Getter

I'm trying to understand how I can properly type a Vuex Method-Style getter .我试图了解如何正确键入Vuex Method-Style getter Here's aFiddle , and the code:这是一个Fiddle和代码:

interface IData {
    name: string;
}

type IGetters = {
    data(getters: IGetters): IData;
    getDataByKey: (getters: IGetters) => (name: string) => string;
    getName(getters: IGetters): string;
}

const getters: IGetters = {
    data(getters) {
        return {
            name: 'Hello'
        };
    },
    getDataByKey: (getters) => (name) => {
        return getters.data[name as keyof typeof getters.data];
    },
    getName(getters) {
        return getters.getDataByKey('name');
    }
}

The issue I'm having is getName .我遇到的问题是getName When invoking getDataByKey , TS throws TS-2345 Argument of type 'string' is not assignable to parameter of type 'IGetters'.调用getDataByKey时,TS 抛出 TS-2345 Argument of type 'string' is not assignable to parameter of type 'IGetters'. To me, it seems like it thinks I need to call the function that has (getters) as the params, but that's not how this works in Vuex.对我来说,它似乎认为我需要调用以(getters)为参数的函数,但这不是 Vuex 中的工作方式。

I saw this SO answer , and I tried to implement what was done, but it didn't work, so I'm pretty sure I didn't implement it properly.我看到了这个SO answer ,我试图实现所做的事情,但它没有用,所以我很确定我没有正确实现它。 Does anyone have any suggestions?有没有人有什么建议?

It looks like per Vuex's definition of a getter ( export type Getter<S, R> = (state: S, getters: any, rootState: R, rootGetters: any) => any; ), they use any to get around this issue, which isn't ideal, but it's at least an answer.看起来每个 Vuex 对getter的定义( export type Getter<S, R> = (state: S, getters: any, rootState: R, rootGetters: any) => any; ),他们使用any来解决这个问题,这并不理想,但至少是一个答案。 My IGetters definition would turn into:我的IGetters定义会变成:

type IGetters = {
  data(state: State, getters: any): IData;
  getDataByKey: (state: State, getters: any) => (name: string) => string;
  getName(state: State, getters: any): string;
};

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

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