Is it possible to generate type definitions for inner classes?

I'm currently exploring the usage of TypeScript within a Salesforce project involving RemoteObject

One challenge I'm facing is creating typings for the external JavaScript object syntax.

For example, in JavaScript:

var ct = new RemoteObjectModel.Contact({
    FirstName: "Aldo",
    LastName: "Michaels",
    Phone: "(415) 555-1212"
});

The stumbling block lies in new RemoteObjectModel.Contact(). How can I define an interface for this?

Below is a snippet of the code I'm attempting to compile:

import React from 'react'
import ReactDOM from 'react-dom'

declare module RemoteObjectModel {
   export class Account implements IRemoteObject {
       constructor();
       get;
       set;
   }
}

interface IRemoteObject{
    get(field: string): any;
    set(field: string, value: string): any;
}

interface IAppProps{
    remoteObjectModel: RemoteObjectModel
}

export class App extends React.Component<IAppProps, {}>{
    public state : IAppState;

    constructor(props : IAppProps) {
        super(props);

        this.state = {
            accounts: 0
        };
    }

    public render(){
        let account: IRemoteObject = new this.props.remoteObjectModel.Account({
            Name : 'hello!',
            Active : true
        });
        console.log(account);
        return (
            <div>
                New Accounts: {this.state.accounts}
                Account: {account.get('Name')}
            </div>
        )
    }
}

//set on the global state
declare var remoteObjectModel : IRemoteObjectModel;

ReactDOM.render(<App remoteObjectModel={remoteObjectModel} />, document.getElementById('app'));

However, there's an issue with IAppProps:

message: 'Cannot find name 'RemoteObjectModel'.'

I'm also uncertain if my question title accurately reflects the problem (please update as needed!)

Answer №1

If the class RemoteObjectModel is already defined, you cannot nest another class like Contact within it.

However, with TypeScript's feature of declaration merging, you can create a namespace named RemoteObjectModel alongside the class (or interface) of the same name. Within this namespace, you can then define the class Contact (remember to export it for visibility outside the namespace).

This approach allows TypeScript to differentiate between the standalone use of RemoteObjectModel referring to the class and RemoteObjectModel.something referring to the namespace.

An example implementation would look something like this:

class RemoteObjectModel {
    someProperty: string;
    constructor() {
        this.someProperty = 'someValue';
    }
}

namespace RemoteObjectModel {

    export class Contact {
        FirstName: string;
        LastName: string;
        Phone: string;

        constructor(values: ContactProperties) {
            Object.assign(this, values);
        }
    }
}

interface ContactProperties {
    FirstName: string;
    LastName: string;
    Phone: string;
}

var ct = new RemoteObjectModel.Contact({
    FirstName: "Aldo",
    LastName: "Michaels",
    Phone: "(415) 555-1212"
});

You can also define a constructor signature in the RemoveObjectModel class to enable calling new remoteObjectModel.Contact() as if Contact is defined on the instance too:

class RemoteObjectModel {
    someProperty: string;
    Contact: {new(p: ContactProperties): RemoteObjectModel.Contact}
}

namespace RemoteObjectModel {

    export class Contact {
        FirstName: string;
        LastName: string;
        Phone: string;

        constructor(values: ContactProperties) {
            Object.assign(this, values);
        }
    }
}

interface ContactProperties {
    FirstName: string;
    LastName: string;
    Phone: string;
}

const remoteObjectModel = new RemoteObjectModel();

var c2 = new remoteObjectModel.Contact({
    FirstName: "Aldo",
    LastName: "Michaels",
    Phone: "(415) 555-1212"
});

Alternatively, you can declare an instance property Contact typed as the 'static part' of the Contact class (usable as a constructor), using typeof Contact:

class RemoteObjectModel {
    someProperty: string;
    Contact: typeof RemoteObjectModel.Contact
    constructor() {
        this.Contact = RemoteObjectModel.Contact;
    }
}

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

Guide on successfully importing a pretrained model in Angular using TensorFlow.js

I need help with uploading a pretrained Keras model to my existing tensorflow.js model and then making simple predictions by passing tensors in the correct format. The model is stored locally within the project, in the assets folder. export class MotionAn ...

Enhancing Javascript performance with the power of the V8 engine and Typescript

I recently came across an informative article discussing V8 engine and javascript optimization. How JavaScript works: inside the V8 engine + 5 tips on how to write optimized code The article highlights some key recommendations: a. V8 engine utilizes hid ...

Is it possible for Typescript interface A to extend B while lacking certain properties from B?

My confusion lies in understanding how TypeScript interfaces function effectively. Here's what I currently have: import type { Socket, Handshake } from 'socket.io'; import type { Session } from './session'; export interface Sessio ...

Broadening Cypress.config by incorporating custom attributes using Typescript

I'm attempting to customize my Cypress configuration by including a new property using the following method: Cypress.Commands.overwrite('getUser', (originalFn: any) => { const overwriteOptions = { accountPath: `accounts/${opti ...

There was an error parsing the data from the specified URL (http://localhost:8000/src/client/assets/data.json

Hey there, I'm a newcomer to Angular and I'm having trouble reading a JSON array from a file. Every time I try, it gives me a "failed to parse" error. Can someone please provide some guidance? Here is my folder structure: src --assets ---a ...

Using the *ngFor directive within an <ng-container> element and wrapping it in an <ng-template> is a great way to dynamically display various data in

I have encountered an issue with my HTML file. The initial content within the ng-container tag is displaying data correctly. However, upon clicking the button to open the details panel, which utilizes the ng-template, only the first data entry from the arr ...

What is it about Typescript's "typeof function" that meets the Generic Condition of "extends (...args: any[]) => any"?

Consider the code snippet below: type Params<F extends (...args: any[]) => any> = F extends ((...args: infer A) => any) ? A : never; const fn00 = (name: string, age: number, single: boolean) => true type test07 = Params<typ ...

Import TypeScript files with RequireJS

I'm looking for some clarification on RequireJS. Right now, I compile all my Typescript files into one JS file. If I switch to RequireJS, does that mean I won't have just one JS file anymore? As I understand it, RequireJS dynamically loads JS f ...

Encountering the error "No overload matches this call" while utilizing useQuery in TypeScript may indicate a mismatch in function parameters

My issue lies with TypeScript and types. Here is the API I am working with: export const clientAPI ={ //... getOptions: async (myParam: number) => get<{ options: Options[]; courses: any[] }>(`/courses?myParam=${myParam}`)().then((result) =& ...

Updating Dropdown Selection in Angular 9 and 10

Is there a way to set attributes to "Selected" in HTML options based on a condition from a *ngFor loop in response.body of the component ts file? Below is the dropdown code: <select [(ngModel)]="customer.id"> <option *ngFor="let location of lo ...

Adjusting the background opacity when the sidebar is open in a React + Typescript project

I am currently working on customizing a sidebar using the react-pro-sidebar library along with React and Typescript. The sidebar layout seems to be in order, but I am facing difficulty in adjusting the background color of the rest of the screen when the si ...

Using react-google-charts to create visually appealing dual-Y stacked bar charts

I am currently working on developing a bar chart with specific criteria in mind. My data follows the format: [month, region, totalSalesForCompanyA, totalSalesForCompanyB] I have successfully implemented the following charts: A dual-Y bar chart where mo ...

Encountering an error when attempting to access undefined property while using a method as a callback

Exploring OOP and angular is new to me. I am currently trying to implement a reusable table with pagination that triggers an API request when the page changes (pagination within the table component). The issue arises when I attempt to access my method usi ...

When Typescript compiles to JavaScript, it may result in code that appears to be a function

In the following typescript code snippet: export enum UID { FACTORY, ROBOT } we see how it compiles to javascript: (function (UID) { UID._map = []; UID._map[0] = "FACTORY"; UID.FACTORY = 0; UID._map[1] = "ROBOT" ...

Encountering a failure in the NativeScript 2.0 [1.7.1] build specifically at the 'processF0DebugResources' stage when including gulp dependencies in the 'devDependencies' section

Encountering a build failure with NativeScript 2.0 (using NativeScript-Angular) when gulp related dependencies are added to the 'devDependencies' section and running [tns build android]. The error occurs at 'processF0DebugResources' and ...

error TS2559: The type 'BookInterface[]' does not share any properties with the type 'BookInterface'

Hello, I am currently working on a project using Angular 7 and encountering the error TS2559: Type 'BookInterface[]' has no properties in common with type 'BookInterface'. Despite making changes to the code, the issue persists. Below is ...

Navigating VSCode for Correct Import Setup

My root app directory has a structure consisting of the following folders: /app/ /environments/ Within the /app/ folder, there is a file named Helper.ts located in the helpers/ subdirectory: /app/helper/Helper.ts Inside this file, I attempted to import ...

What is the best way to transpile TypeScript within the Astro framework?

Recently, I decided to dive into exploring Astro for a couple of upcoming projects. In my research, I delved into the script and typescript sections of the documentation (), as well as (). However, I found the workflow somewhat counterintuitive and struggl ...

Error: AppModule requires an array of arguments in order to function properly

Upon successfully compiling my Angular application and running ng serve, I encountered the following error in the browser console. AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: Arguments array must have arguments. at injectArgs (core.js:1412) at c ...

Converting JSON Arrays into Typed Arrays in NativeScript using Typescript

Can someone assist me with a problem I'm facing while learning NativeScript? I am trying to read a txt file that contains JSON data and then assign it to an Array called countries. However, despite my efforts, I have not been successful. The code sni ...