Search code examples
nativescripttslintnativescript-angular

How to use someClass.android.ts and someClass.ios.ts without errors


I'm using nativescript angular. I have a class called SomeClass that access the native API of iOS and Android separately.

I've written two files:

someclass.android.ts

export class SomeClass {
    someFunction() {
        if(isAndroid) {
            // do some android specific code
        }
    }               
}

someclass.ios.ts

export class SomeClass {
    someFunction() {
        if(isIOS) {
            // do some ios specific code
        }
    }               
}

Now, in app.component.ts, I'm using SomeClass like this:

import { SomeClass } from './../shared-code/someclass';

without .android.ts or .ios.ts, to enable nativescript to pick the right file depending on the running platform.

and then in the code, I user SomeFunction like this:

...
const someClass = new SomeClass();
someClass.someFunction();
...

With this setting, everything works perfectly on both iOS and Android, but I get the following error

error TS2307: Cannot find module './../shared-code/someclass'.

Do you have any idea how to tell nativescript/tslint to take into account the .android and .ios files and not to display this error?

Thanks


Solution

  • Here's the solution:

    Alongside 'someclass.ios.ts' and 'someclass.android.ts', create a definitions file and name it 'someclass.d.ts' (Not index.d.ts). No need to put the files in a separate folder.

    In someclass.d.ts, export declare the class like this:

    export declare class SomeClass {
        /**
         * someFunction, is a function that does this and that (description)
         */
        someFunction(): void;
    
    }
    

    Then, you can use this from another file like this:

    In app.component.ts:

    import { SomeClass } from './../shared-code/someclass';
    

    Remember to use /someclass without any extensions. This would solve build and tslint errors.