Enhance tns-platform-declarations with NativeScript

I am working on a NativeScript project and I am trying to incorporate the RecyclerView from Android Support Library. I have added the dependency in the

app/App_Resources/Android/app.gradle
file:

// Uncomment to add recyclerview-v7 dependency
dependencies {
    compile 'com.android.support:recyclerview-v7:+'
}

After reading discussions on GitHub issue#2295 and other related issues, I found out that I can include tns-platform-declarations to get definition files for native android/ios libraries. I installed them and followed the tns platform declarations documentation

My goal is to compile the following code snippet:

import { ContentView } from "ui/content-view";

declare var android: any;

export class OptimizedListView extends ContentView {

  private _android: android.support.v7.widget.RecyclerView;

  public _createUI() {
    this._android = new android.support.v7.widget.RecyclerView(this._context);
  }

};

Even though declaring the var android as shown above fixes one reference to RecyclerView, I still receive an error for the initial reference to RecyclerView:

message: 'Namespace 'android.support.v7.widget' has no exported member 'RecyclerView'.'

I also attempted to declare the RecyclerView class separately but without success:

export declare class RecyclerView extends ContentView {}

I understand that the definitions in tns-platform-declarations only go up to android.support.v7.widget.

Setting "noEmitOnError" to false as a workaround doesn't seem optimal.

So, how can I expand this declaration to include

android.support.v7.widget.RecyclerView
without running into compilation issues?

Versions:

  • "nativescript-dev-typescript": "^0.3.2"
  • "tns-platform-declarations": "^2.4.0-2016-09-28-1"
  • "typescript": "^2.1.1"
  • "tns-core-modules": "next"

Answer №1

Instead of using the tns-platform-declarations due to its poor performance on machines with less than or equal to 8GB RAM, I opted to create my own typings file named my-typings.d.ts at the project root directory. This file included an augmenting type definition for RecyclerView, which would be automatically recognized by TypeScript's default tsconfig.json. If needed, manual configuration through the use of exclude, include, or files expressions could also be implemented.

To ensure that the TypeScript compiler could locate the defined ambient global namespace, a reference path like

/// <reference path="path/to/RecyclerView/file.d.ts" />
was added within the file.

// Namespace and class definitions

The usage of namespaces allowed for the emulation of nested object properties, such as android.view.xxx. This method was particularly useful when dealing with inner classes in Java, as TypeScript does not support nested class statements.

In cases where the type (e.g., android.view.ViewGroup) was utilized, a class with the same name as the namespace had to be defined to avoid the error:

no exported member xxx

Even if the class type was explicitly declared with export, it was unnecessary since the namespace had already been globally declared.

To extend native Java types using extend, I created static methods like

static extend(AdapterImpl): { new () }
for relevant classes. The return type of these methods could then be instantiated using new.

I hope this information proves helpful to others facing similar issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Typescript and react-redux with a Stateful Component: The parameter type 'typeof MyClass' does not match the expected component type

I've been trying to dive into the world of Typescript, React, and Redux. However, I've hit a roadblock at the moment. This is the error I encountered: ./src/containers/Hello.tsx [tsl] ERROR in /home/marc/Development/TypeScript-React-Starte ...

Discover the Preferred Network Type Configuration

I am currently attempting to retrieve the setting for Preferred network type from the device, but I have not been able to find any Android APIs that offer access to this information. Scenario: My goal is to monitor the Preferred network type and connecte ...

The application's in-app billing feature is experiencing issues with processing actual transactions

My app's alpha version is up and running. I've opened the alpha for testing. Successfully tested in-app billing using a test account (no money charged). Also, successfully tested the purchase with static response. However, when trying to test r ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

How should I proceed if a TypeScript definition file that I am relying on is lacking a specific definition?

I have encountered an issue while using the React type definitions for my project. The focus method is missing on elements in the array returned by the refs property, which prevents me from getting a specific example to work. The compiler error states: pro ...

Looking to trigger an action with a click on a variety of color choices?

I have successfully downloaded the code from the following link: https://github.com/dlazaro66/WheelIndicatorView Upon running the sample application, I observed the following output: https://i.sstatic.net/muLgz.png Now, I am interested in performing dif ...

Obtaining and storing an array of JSON data from Socket.IO

Upon receiving an array of objects from my server, it looks like this: Log.i(TAG, "Destinos obtenidos: "+ destinosRuta); The log value is - Destinos obtenidos [{"Latitud":41.40404,"nombreDestino":"Barcelona","IDR":5,"IDD":6,"Longitud":2.168679},{"Latit ...

Using Flickity API in Vue 3 with Typescript Integration

I have encountered an issue with implementing Flickity in my Vue 3 application. Everything works perfectly fine when using a static HTML carousel with fixed cells. However, I am facing difficulties when attempting to dynamically add cells during runtime us ...

Variations in comparing tuple types in TypeScript

Exploring the TypeScript Challenge, there is a particular problem known as IsNever. The task at hand is to create a type called IsNever that takes input of type T. If the resolved type equates to never, the output should be true; otherwise, it should be fa ...

Here's how you can retrieve URL parameters in NextJs, such as `userid/:this_is_a_param`

I'm struggling to retrieve URL parameters using Next.js. I normally do this with Express by getting a :param from the URL like this: users/:userid/ console.log(req.params.userid) All I've been able to do is get the "userid" from the URL like thi ...

showcasing an assortment of images and selecting them with a click

I am working on a project that involves displaying random images and detecting if the user clicks on the correct image. I have defined an array of image IDs that I want to use for this purpose. private int[] imgId = new int[] { R.drawable.info_mna, ...

Converting ts files to js: A comprehensive guide

I am looking for a way to transform my TypeScript files into JavaScript files smoothly. The conversion process goes well with the command: nodemon --watch assets/ts --exec tsc assets/ts/*.ts --outDir assets/js However, I have encountered an issue where im ...

Access the Ionic2 App through the Slider option

Trying out Ionic 2 and facing an issue. Created a default side-menu app from CLI with a slider. Need to start the actual side-menu app from the last slide on button click or anchor link. My app.ts: @Component({ templateUrl: 'build/app.html' }) ...

Testing Angular: How to Unit-test HttpErrorResponse with custom headers using HttpClientTestingModule

In the code snippet below, I am attempting to find a custom header on error: login(credentials: Credentials): Observable<any> { return this.http.post(loginUrl, credentials) .pipe( catchError((httpErrorResponse: HttpErrorRespo ...

Having issues with TypeScript custom commands in Cypress?

Update: https://github.com/cypress-io/cypress/issues/1065#issuecomment-351769720 Removing an import from my commands.ts fixed it. Thanks In the process of transitioning my cypress project to use TypeScript, I am following the guidelines provided at https: ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

Encounters an android:src error

Issue: The error message "Error: No resource found that matches the given name (at 'src' with value '@drawable-hdpi/ic_launcher')" is appearing. Can someone help me understand why I am encountering this error? <TextView ...

The use of await can only occur inside an async function

Can someone explain the proper placement of the async keyword for me? I've tried a few different spots, but keep encountering the same error. async addNewCategory() { let alert = this.alertCtrl.create({ title: 'New Category', ...

Is there a proper way to supply createContext with a default value object that includes functions?

As I was creating my context, I set an initial state and passed the necessary functions for useContext. Although this method is functional, I'm concerned it may present challenges in larger projects. Does anyone have suggestions for a more efficient a ...

Unable to determine the ComputeDistanceBetween method

I am currently working with the Google Maps API and utilizing the Map Fragment Class. My goal is to calculate the distance between two points on the map, but I keep encountering an error stating that the method ComputeDistanceBetween cannot be resolved. ...