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

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...

Is it possible to use an object's attribute as a switch case in TypeScript with useReducer?

I am attempting to convert switch case String into an object, but for some reason typescript is misunderstanding the switch case within useReducer: Prior to version update, everything was functioning correctly: export const LOGIN_USER = "LOGIN_USER&qu ...

Exploring Angular: The Dynamic Declaration of object.property in ngModel

<input [(ngModel)]="Emp."+"dt.Rows[0]["columnname"]"> This scenario results in an undefined value In my current project, I am leveraging the power of a MVC CustomHtmlHelper to generate textboxes dynamically based on database schema. The textbox ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

java.lang.IllegalArgumentException: The provided string is either empty or null

I have recently started working with Firebase and encountered an issue while trying to implement a login functionality. Whenever I attempt to click the button without filling in the fields, the application crashes even though I have written code to handle ...

Using the useRef hook to target a particular input element for focus among a group of multiple inputs

I'm currently working with React and facing an issue where the child components lose focus on input fields every time they are re-rendered within the parent component. I update some state when the input is changed, but the focus is lost in the process ...

When using Ionic 3 on an Android device, the keyboard is causing the tabs and app content to shift upwards

I'm currently working on an Ionic 3 app and encountering a problem. Whenever I click on the search function, the keyboard opens and pushes all the content of the app to the top. Here is the code for the tabs and view: <ion-tabs color='navbar ...

Comparing the functions of useMemo and the combination of useEffect with useState

Is there a benefit in utilizing the useMemo hook instead of using a combination of useEffect and useState for a complex function call? Here are two custom hooks that seem to function similarly, with the only difference being that useMemo initially returns ...

The transparency feature using rgba is not supported in the Chrome browser for Android

Have you noticed the transparency effect in certain divs using the rgba CSS property? Strangely, Chrome on my ASUS tablet and Samsung S3 mini Galaxy smartphone does not seem to support this feature. Surprisingly, Internet Explorer does! Any insights on w ...

TS fails to recognize any additional properties added to the constant object

When working on a function that should return an object with properties 'a' and 'b', I am defining the object first and then adding values to it later: const result = {}; result.a = 1; result.b = 2; return result; However, TypeScript i ...

Identifying a web application functioning as a homescreen app within the Android Stock Browser

We are in the process of developing a web application that needs to function as a standalone or homescreen app. While we can identify if it is being accessed from Chrome or Safari using window.navigator.standalone or window.matchMedia('(display-mode: ...

In Typescript with Vue.JS, the type 'Users[]' does not include the essential properties of type 'ArrayConstructor' such as isArray, prototype, from, of, and [Symbol.species]

Embarking on my journey with typescript and vuejs, I stumbled upon a perplexing error that has halted my progress for the past 48 hours. The error message reads as: Type 'Users[]' is missing the following properties from type 'ArrayConstruct ...

Is there a way to receive a comprehensive report in case the deletion process encounters an error?

Currently, I am performing a delete operation with a filter based on 2 fields: const query = await Flow.deleteOne({ _id: flowId, permissions: currentUser!.id, }); After executing the delete operation, I inspect the query object to determine its su ...

How to Delete Multiple Rows from an Angular 4 Table

I have successfully figured out how to remove a single row from a table using splice method. Now, I am looking to extend this functionality to remove multiple rows at once. html <tr *ngFor="let member of members; let i = index;"> <td> ...

Submitting a form using an anchor tag in Angular 8: A step-by-step guide

I have a question about how to submit form data using hidden input fields when a user clicks on an <a> tag. <form action="/submit/form/link"> <input type="hidden" [attr.value]="orderNumber.id" /> <input type="hidden" [attr.value]= ...

Initiating Angular APP_INITIALIZERThe Angular APP_INITIALIZER

I am a newcomer to Angular and currently utilizing Angular6 for development purposes. I have a specific query regarding my app. Before the app initializes, I need to invoke three services that provide configurations required by the app. Let's refer to ...

Typescript: Implementing a generic function with the flexibility of an optional parameter

Having some difficulty writing a generic function with an optional parameter type Action<TParameters = undefined> = (parameters: TParameters) => void const A: Action = () => console.log('Hi :)') // This works as expected const B: ...

When initialized within an object, Angular may identify a field as undefined

Whenever I attempt to access a property of the object named "User," it shows up as undefined. However, upon logging the complete object to the console, the field appears with the necessary data. Here is the console log output: perfil.component.ts:42 unde ...

Unable to see Next.js page in the browser window

I have set up a next.js project with App Router and my file structure under the app folder looks like this: *some other files* . . user | [id] | | page.tsx | @users | | page.tsx | layout.tsx | page.tsx I am ...

Excessive ReCaptcha Pop-ups in Android's WebView causin' inconvenience

I've developed a straightforward Android app that functions as a WebView application. The main purpose of this app is to provide users with access to example.com and enable them to engage with the website. Upon launching the app for the first time, us ...