Organizing TypeScript files and code within an ASP.NET project

Currently, I am working on an ASP.NET project using .NET 4.6 and Visual Studio 2015. The business logic is primarily written in C#, but there is also a significant amount of client-side logic involved. To help organize my client-side code in a way similar to how I'm used to with C#, I decided to use TypeScript.

However, as I delved deeper into TypeScript, I realized that it differs significantly from C#. One major issue I encountered is that TypeScript does not support the simple class-per-file rule, which would allow me to include multiple classes or interfaces in a single file.

This limitation becomes problematic when defining ViewModel classes and initialization scripts for different pages where I need to utilize various models and utilities.

In my search for solutions, I came across two approaches:

A: Encapsulating each class within a namespace:

// Similar to C# using
import utils = App.Code.Utils;

namespace App.Code {
    export class ZipCodeValidator {

        public zipCode: string;

        public validate(): boolean {
            let stringValidator: utils.StringValidator = new utils.StringValidator();
            
            // TODO validation
            return true;
        }
    }
}

While initially satisfied with this solution, I soon found out that managing file order manually can become cumbersome, especially as the number of files increases due to the class-per-file rule.

B: Using Modules:

import { StringValidator } from "./Utils/StringValidator";

export default class ZipCodeValidator {
    public zipCode: string;

    public validate(): boolean {
        let stringValidator: StringValidator = new StringValidator();
        
        // TODO validation
        return true;
    }
}

Although using modules eliminates the need to manage file order manually, importing individual classes can be tedious. Additionally, separating source into different JS files based on directory structure seems challenging.

Ultimately, I am looking for a better approach to streamline my TypeScript development process. Can you suggest any tools, plugins, or techniques to facilitate this? I want to leverage TypeScript efficiently without resorting to manual work. Hopefully, the insights shared here will benefit others facing similar challenges.

Thank you.

Answer №1

The method I prefer involves utilizing approach B and organizing modules. By gathering all the commonly used modules in a wrapper module, they can be easily re-exported for seamless importing into other modules.

Here is an example:

AllUtils.ts

export * from './UtilClass1';
export * from './UtilClass2';
export { UtilClass3 as SomethingElse } from './UtilClass3';

This method enables you to import all your classes using a single statement like this:

import * as utils from './AllUtils';

let myUtil = new utils.UtilClass1();

I have found that using this approach allows Intellisense to work effectively in VS2015. Another advantage is the ability to exclude or rename specific classes when re-exporting. While you still need to add them individually to the wrapper file initially, this only needs to be done once.

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

What is preventing me from inheriting from the abstract class System.Enum?

According to MSDN, System.Enum is described as an abstract class: [SerializableAttribute] [ComVisibleAttribute(true)] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible MSDN also states the purpose of an abstract class in the ...

Is there a problem with handling custom images in Next.js and TypeScript with React Quill?

I am currently facing challenges with integrating react-quill into my TypeScript Next.js project. Specifically, I am encountering issues related to typing and handling ref. Any assistance in resolving these problems would be greatly appreciated. Below is ...

Ways to display the complete array contents

If I create a class named Car with various attributes like number, brand, model, and kilometers, as shown below: public class Car { private string number; private string brand; private string model; private double kilometers; public ...

Tips for dismissing loader in Ionic 4

I'm struggling to programmatically dismiss the loader. I've developed two separate methods - one for displaying the loader and another for dismissing it. These methods are called accordingly when needed. async showLoader() { this.loader = a ...

Facing an Issue with Angular Reactive Form - Encountering 'formDirective is null' Error

Here is the form I have created: <div class="container"> <form formGroupName="checkoutForm"> <section> <div class="row"> <div class="col col-12 col-lg-8"> ...

Vue3 with Typescript may either display an error message or remain empty when handling props

I've been attempting to utilize the default Quasar card component in order to display data received from props. Unfortunately, I haven't had any success as my component remains empty and I keep encountering various errors with each attempt. Rece ...

Observable task queuing

Here's the scenario: In my application, the user can tap a button to trigger a task that takes 2 seconds to complete. I want to set up a queue to run these tasks one after another, in sequence. I am working with Ionic 3 and TypeScript. What would be ...

Sorting an array of numbers in TypeScript using the array sort function

Looking to organize an array based on ID, comparing it with another array of numbers var items:[] = [{ item:{id:1},item:{id:2},item:{id:3},item:{id:4} }] var sorted:[] = [1,3,2,4]; Output: var items:[] = [{ item:{id:1},item:{id:3},item: ...

Function that determines the value based on the type of item in the collection

Below is a code snippet that adds objects to the MemoryCache. These objects may have different types. I need a method that can retrieve an object from the MemoryCache, but the return type may vary. In my example, there are 2 types of returns but there co ...

Getting an error in React when using Typescript with a functional component? The issue might be that you are trying to assign a type 'boolean' to a type 'ReactElement<any, any>'

Recently, I set up a project that utilizes TypeScript in conjunction with React. As part of the project, I created a Layout component that relies on the children prop. Below is the current code snippet: import React from 'react'; type LayoutProp ...

What is the best way to restrict string patterns in TypeScript?

I have a type definition that looks like this: type ActionType = 'TypeA' | 'TypeB' | 'TypeC' | 'TypeD'; I need myActionType to be a string that is either one of the ActionTypes or a combination of ActionTypes separa ...

ASP.Net MVC page is sending data to the controller without displaying the record ID in the address bar

In my web application, I have implemented a Razor page to display a list of meetings. Each meeting has a unique ID which is associated with a link. Clicking on this link loads another Razor view that shows the details of the selected meeting. Within this v ...

Utilizing the input element to modify the font color of the title upon clicking the button

I've been honing my skills in Angular and facing an issue with altering the font color of a variable called title. I'm struggling to figure it out. Take a look at the code snippet from tools.component.ts: [...] title: string = 'Add note ...

Implementing a dynamic star rating system in Angular

I am working with an array of ratings that looks like this: "rating": [ { "sno": 1, "question": 13, }, { "sno": 2, ...

Under what circumstances would you need to manually specify the displayName of a React component?

After coming across an article (linked here: https://medium.com/@stevemao/do-not-use-anonymous-functions-to-construct-react-functional-components-c5408ec8f4c7) discussing the drawbacks of creating React components with arrow functions, particularly regardi ...

How do I define the type of a class property in TypeScript?

I am currently working on my own implementation of Client-side rendering and I need to define the data structure for my route object. The format is shown below: import Post from './Post' export const route = { path: '/post', c ...

Navigating to another page within an ASP.NET application

I encountered an issue with a piece of code that is supposed to redirect to a specific company page from the request page. The Company page is located in the Companies folder within the website folder hierarchy, while the request page is in the Requests fo ...

Missing Icons in ContextMenu

I have a variety of images that serve as icons for different ContextMenu Items: <UserControl.Resources> <Image x:Key="DeleteIco" Source="pack://application:,,,/MyProject.myControl;component/Resources/Delete.ico" Width="16" Height="16"/> ...

Locking state object and properties as read-only in ReactJS/Typescript

I have an object from a third-party class and I want to ensure that its properties are read-only. This means that I do not want to be able to change the state with this.state.object.props = "xx"; The structure of the object is as follows: class ThirdPart ...

Regular expressions can be used to capture text that falls outside of two specific phrases

Looking to extract text from text files, but need to ignore specific sections. The sections to skip over will be indicated by the following markers: --- start private --- and will end with: --- end private --- It doesn't matter if the markers thems ...