Search code examples
typescriptnuxt.jsvuex

TypeScript/Nuxt.js/Vuex: Access methods from imported class


I am building a nuxt.js app with typescript and want to separate the API Calls from the vuex store. But it seems like I can not use the methods when I import the class. The compiler also only says TS1005: ',' expected. when I am trying to call a method.

apiClient.ts

export default class apiClient {
    helloWorld() {
        console.log('Hello World');
    }
}

products.ts:

import ApiClient from '../services/apiClient';

export const actions = {
  ApiClient.helloWorld();
};

tsconfig.json

 "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "baseUrl": ".",
    "paths": {
      "~/*": [
        "./src/*"
      ],
      "@/*": [
        "./src/*"
      ]
    },
    "types": [
      "@types/node",
      "@nuxt/types",
      "@nuxtjs/axios"
    ]
  },

Solution

  • There are multiple issues with your code.

    The first problem is that you can't define your actions like that. You are writing your function directly into the actions object, which is not how objects work. You need to define a key and assign your function to that, like this:

    export const actions = {
      helloWorld: ApiClient.helloWorld,
    };
    

    Notice the missing parentheses, as you are assigning your function and not executing it.

    But that code will still not compile, as you defined your methods in a class. There is nothing wrong with doing so, but if you do it that way you will have to instantiate your class with the new keyword (or you could make your class static, if you know how to do that):

    import ApiClient from '../services/apiClient';
    const client = new ApiClient();
    
    export const actions = {
      helloWorld: client.helloWorld,
    };
    

    In your case I wouldn't use a class in the first place. You can export your functions directly, which is way easier:

    export const helloWorld = () => {
      console.log('Hello World');
    };
    

    Importing is way easier now too. You can also omit the key, if you keep it the same name as you exported it:

    import { helloWorld } from '../services/apiClient';
    
    export const actions = {
      helloWorld,
      // or use a different name:
      hello: helloWorld,
    };
    

    I hope this fixes your problem and you understand why it didn't work.