The Concept of Static Block in TypeScript

For the purpose of testing Network Encoding/Decoding Logic, I have implemented a pair of test cases in both Java and JavaScript. These tests utilize Data Providers which essentially consist of various Constants.

In my Java test case, I have a Data Provider that utilizes a static block to generate a random byte array for one of the classes being tested. Here is an example:

    public static final byte[] BYTE_ARRAY_RANDOM = new byte[4 * 1024];
    static {
        new Random().nextBytes(BYTE_ARRAY_RANDOM);
    }
    public static final FileBody FILE_BODY_RANDOM = new FileBody(BYTE_ARRAY_RANDOM);

Now, when trying to replicate this in TypeScript, I encountered a compilation error due to incorrect implementation of the static block:

    public static BYTE_ARRAY_RANDOM: Uint8Array = new Uint8Array(4 * 1024);
    static {
        BYTE_ARRAY_RANDOM.set(pseudoRandomBytes(bytes.length));
    }
    public static FILE_BODY_RANDOM: FileBody = new FileBody(TestDataProvider.BYTE_ARRAY_RANDOM);

Despite attempting several other methods, I have not been successful in finding a suitable solution so far.

Therefore, I am seeking guidance on how to achieve similar functionality in JavaScript. My aim is to create a Constant that provides a unique random byte array each time the tests are executed.

In simpler terms, how can I make this constant value static in TypeScript?

    let bytes = new Uint8Array(4 * 1024);
    bytes.set(pseudoRandomBytes(bytes.length));
    let fileBody = new FileBody(bytes);

Answer №1

It appears that TypeScript does not have native support for static blocks. In order to address this issue, you can utilize a helper function:

class Foo {
    public static bytes = createRandomBytes(4 * 1024);
    public static fileBody = new FileBody(Foo.bytes);
}

function createRandomBytes(length: number) {
    const bytes = new Uint8Array(length);
    bytes.set(pseudoRandomBytes(bytes.length));
    return bytes;
}

Answer №2

Did you know that TypeScript now supports static initialization blocks as of version 4.4 released in August 2021?

Check out the official announcement here

This feature is also available in JavaScript:

Learn more about static initialization blocks in JavaScript here

The syntax for using static initialization blocks is straightforward, just like this:

static {
    // Your code here
}

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

In React Router v6, you can now include a custom parameter in createBrowserRouter

Hey there! I'm currently diving into react router v6 and struggling to add custom params in the route object. Unfortunately, I haven't been able to find any examples of how to do it. const AdminRoutes: FunctionComponent = () => { const ...

Angular 14 introduces a new feature that automatically joins open SVG paths when dynamically rendered from a data object

I developed an application to convert SVG code into a JSON object that can be stored in a database. Another app was created to dynamically display the rendered result on a webpage. The rendering output appears as shown in this image: Upon rendering, it se ...

Utilizing Angular 2 alongside ngrx/store for seamless updates to specific properties within the state object without disrupting the entire structure

I am facing an issue where I need to update a property of a state object without creating a new object. Is there a way to add or update a single property without replacing the entire object? Below is the reducer code: const initialState = { all: [], ...

Click function for mat-step event handler

Is it feasible to create a click event for the mat-step button? I want to be able to add a (click) event for each mat-step button that triggers a method. Essentially, I am looking to make the mat-step button function like a regular button. You can find mo ...

Steps for sorting items from a list within the past 12 hours

I'm currently working with Angular and I have data in JSON format. My goal is to filter out items from the last 12 hours based on the "LastSeen" field of the data starting from the current date and time. This is a snippet of my data: { "Prod ...

Is it possible for us to perform an addition operation on two or more items that belong to the same

I am faced with a challenge involving 3 objects of the same type, each having different values for their properties. My goal is to add them together as illustrated below: Consider this scenario: objA = { data: { SH: { propertyA: 0, propertyB: ...

What is the best way to limit the types of function parameters in TypeScript based on whether the parameter index is even or odd?

My goal is to create a function with an unlimited number of parameters, where the type of each parameter is determined by whether its index is odd or even. For example: flow(isMachineReady(), 'and', isWaterHot(), 'or', isMilkHot(), &ap ...

Unable to set textAlign column property in Inovua React Data Grid using typescript

I am currently facing an issue with centering the content of each grid cell in Inovua RDG. A frustrating TypeScript error keeps popping up: Type '{ name: string; header: string; textAlign: string; defaultFlex: number; defaultVisible?: undefined; }&apo ...

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

Asynchronous problem when using Firebase calls within an Angular ForEach loop

Here's the code snippet I'm working with: getTotalBookListCost(bookList:string[]):number { let cost=0; bookList.forEach(el=>{ this.store.doc("Books/"+el).get().subscribe(data=>{ let temp=<Book>data.da ...

A service worker of unknown origin is currently getting registered

Currently, I am using the service worker provided in create-react-app. After registering it in index.tsx with serviceWorker.register();, everything seems to be working fine. However, upon closer inspection in the dev tools' Application tab, I noticed ...

Submitting information to a server

I have a simple Angular 6 app with follow and unfollow buttons. When you click follow, the number increases. I want to save these follower numbers to a JSON server. Here is the link to the JSON server documentation: JSON Server Documentation To see a dem ...

Unexpected date format displayed by the flat picker calendar

The expected date format is "DD-MM-YYYY" but the shown date format in the UI is "YYYY-MM-DD". Click here to view the UI image Initially, before opening the date picker, the date is displayed in the expected format as "DD-MM-YYYY". Upon opening the date p ...

Angular 8 fails to retain data upon page refresh

I have a property called "isAdmin" which is a boolean. It determines whether the user is logged in as an admin or a regular user. I'm using .net core 2.2 for the backend and Postgre for the database. Everything works fine, but when I refresh the page, ...

Implementing pagination within an Angular 11 Mat-table with grouping feature

Encountering an interesting issue with MatTable pagination and grouping simultaneously. I have two components each with a Mat-table featuring Pagination+Grouping. ComponentOne functions smoothly without any issues. When choosing to display 5 elements pe ...

React: Retrieved information, yet unable to access the properties of the object

After successfully fetching data from an API call and seeing the results in console, I am facing issues with accessing object properties and displaying them. interface Data { data: [] isLoading: boolean } function About() { const [ dataUser, ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...

Insert an HTML element or Angular component dynamically when a specific function is called in an Angular application

Currently, I am working on a component that contains a button connected to a function in the .ts file. My goal is to have this function add an HTML element or make it visible when the button is clicked. Specifically, I would like a dynamic <div> elem ...

Executing a series of imported functions from a TypeScript module

I'm developing a program that requires importing multiple functions from a separate file and executing them all to add their return values to an expected output or data transformation. It's part of a larger project where I need these functions to ...

Tips for integrating Typescript Definition files with Visual Studio 2017

I have a challenge with my ASP.NET Core 2.0 application where I am attempting to incorporate TypeScript and jQuery. While TypeScript integration has been successful, I am facing issues with jQuery as it does not provide me with intellisense. Despite trying ...