How can I access Native api in NativeScript when I use Typescript

TypeScript is strongly typed language and needs an explicit type definition for each variable (e.g. like pow). Instead of casting to any, you could provide definition files pre-generated by NativeScript that will give you typing and IntelliSense for the native Android and iOS APIs.

The latest release of NativeScript by default is creating the app without the platform declaration files (android17.d.ts for Android and ios.d.ts for iOS) and without those files, your TypeScript simply does not know about the native APIs references.
The reason not to include the definition files – those are enormously big and are needed only when the developers are going to use TypeScript (or Angular) + access to native APIs.

The solution:

1.) Install the definition files as a developer dependency

npm i tns-platform-declarations --save-dev

This will install your platform declaraion files in node_modules/tns-platform-declarations

2.) Create references.d.ts in your main app directory and add the following

// SEE the updated paths below

Now you are good to go!

UPDATE (as of October 2017 – with installing tns-core-modules 3.x.x (or above) and tns-platform-declarations 3.x.x (or above)):
The npm plugin now has a different structure so these are the proper paths (create references.d.ts file in the root directory and place the one below)

/// <reference path="./node_modules/tns-platform-declarations/ios/ios.d.ts" />
/// <reference path="./node_modules/tns-platform-declarations/android/android.d.ts" />

Important: Your tsconfig.json should look like this:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "experimentalDecorators": true,
        "lib": [
            "es6",
            "dom"
        ]
    }
}

Leave a Comment