Typescript: Implementing a Class with Generic Type of 3 or 4

I am looking to create a versatile class for squared matrices that can accommodate matrices of any size. My aim is to develop standard methods such as addition and multiplication specifically designed for matrices of equal dimensions.

The objective is to consolidate all matrix types within one class while being able to identify size errors at compile time rather than during execution.

In my attempt, I experimented with using a generic type defined by the union of sizes I want to include, like Class Matrix<S = 3|4>. However, I struggled to figure out how to test if S == 3 or S == 4, and handle it accordingly.

Although I recognize that I could implement an abstract matrix class and extend it for each required size, I find this approach quite laborious...

UPDATE

The solution provided to me seems to be effective. Additionally, I would like to share a helpful tip. To define a multiplication operation with compile-time error checking, you can introduce generic types in the parameters, as demonstrated below:

type Size = 1|2|3|4;
class Matrix<I extends Size, J extends Size> {
    readonly iMax: I;
    readonly jMax: J;
    // add coefficients

    constructor(iMax: I, jMax: J){
        this.iMax = iMax;
        this.jMax = jMax;
        // add coefficients
    }

    mult<K extends Size>(x: Matrix<J,K>): Matrix<I,K>{
        // Compute the product
    }
}

new Matrix(3,3).mult(new Matrix(2,2); // Error catch on compilation.

Answer №1

To utilize the size in runtime code, it needs to be a specific value since TypeScript type information is not accessible at runtime except for enums.

Take note that the example Class Matrix<S = 3 | 4> has two errors:

  1. Class should be written as class (the capitalization matters)
  2. S = 3 | 4 should be S extends 3 | 4 if you intend to impose a constraint on the generic type parameter

Below is a straightforward illustration:

class Matrix<Size extends 3 | 4> {
    readonly size: Size;

    constructor(size: Size) {
        this.size = size;
    }

    example() {
        const { size } = this;
        if (size === 3) {
           console.log("It's three")
        } else {
           console.log("It's four")
        }
   }
}

new Matrix(3).example(); // It's three
new Matrix(4).example(); // It's four
new Matrix(5).example(); // Compilation Error, because matrix doesn't allow 5

Playground link

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

Error: Axios header not refreshing automatically in React. User must manually refresh the page

After logging in, I want to update the JWT token in the header before redirecting to the home page. Login.tsx ... const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); const data = new FormData(event.curr ...

Merge generic nested objects A and B deeply, ensuring that in case of duplicate properties, A's will take precedence over B's

Two mysterious (generic) nested objects with a similar structure are in play: const A = { one: { two: { three: { func1: () => null, }, }, }, } const B = { one: { two: { three: { func2: () => null, ...

Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array? This is my code in my.ts file: initializeItems(){ this.items = [ { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian ...

Conditional generics in TypeScript based on a constructor argument

Within my class structure, I have the following: class Collection<ID extends string | number> { entries: ID[]; constructor(private readonly useStringIds: boolean) {} getIds(): ID[] { return entries.map((entry) => entry.id); ...

Running "npm start" is causing a "SyntaxError: Unexpected token import" error to appear on a typical Angular 2 project when I try to run it

After attempting npm update, npm start then install, I encountered an error right at the beginning of loading the app. It's puzzling that it doesn't recognize "import", which is the first word in the standard bootstrapping file. The stacktrace ...

Ways to conceal button for inactive edit row on a table

I am trying to implement inline editing for a table in my application. The requirement is to hide the "Edit" and "Delete" buttons for all other rows when the user clicks on the edit button of a particular row. I have attempted to achieve this using the c ...

Error in Typescript cloud function: response object is not callable

My cloud function is structured like this: // const {onSchedule} = require("firebase-functions/v2/scheduler"); // The Cloud Functions for Firebase SDK to set up triggers and logging. import * as logger from "firebase-functions/logger&quo ...

generating declaration files for components with accurate type definitions from propTypes

I am in the process of creating a react/js library using rollup. My approach involves utilizing typescript to generate declaration files for my components. Despite having propTypes defined for my components, I have noticed that the emitted .d.ts files as ...

Chart.js Axis Labels Orientation Guidelines

I am currently utilizing chart.js within an Angular 8 environment using Primeng. I am looking to customize the options for my chart as follows: For the y-axis ticks, set textDirection to 'ltr' For the x-axis ticks, set textDirection to 'rtl ...

Ways to determine whether an element is presently engaged in scrolling

Is there a way to determine if certain actions can be disabled while an element is being scrolled? The scrolling may be triggered by using the mouse wheel or mouse pad, or by calling scrollIntoView(). Can we detect if an element is currently being scroll ...

Generating GraphQL Apollo types in React Native

I am currently using: Neo4J version 4.2 Apollo server GraphQL and @neo4j/graphql (to auto-generate Neo4J types from schema.graphql) Expo React Native with Apollo Client TypeScript I wanted to create TypeScript types for my GraphQL queries by following th ...

Can you provide guidance on defining functions using standard syntax and incorporating children in React with TypeScript?

There are multiple ways to type it, such as using the interface React.FC<YourInterface> or explicitly declaring in an interface the type of children as JSX.Element or React.Node. Currently, my approach is: const MyComponent: React.FC<MyInterface& ...

Optimizing Angular 2 TypeScript with enableProdMode for JSPM bundling.QRectPreparing Angular 2

I am in the process of developing an Angular 2 application and packaging it using SystemJS/JSPM. During the development phase, I include the app in index.html: <script src="jspm_packages/system.js"></script> <script src="systemjs.config.js ...

"Encountered a TypeError while attempting to send a server action to a custom

My custom form component, <ClientForm>, is built using Radix Primitives. "use client"; import { FC } from "react"; import * as Form from "@radix-ui/react-form"; const ClientForm: FC = (props) => ( <Form.Root {.. ...

Create typings for object properties in TypeScript

I am inexperienced with TypeScript and am looking to set up types for my object keys. I have explored a few methods to accomplish this, but I am encountering an issue where an error is not triggered when assigning a value of a different type. For example: ...

Angular function triggered by clicking that takes two parameters

Is there a way to pass two arguments in this method? <tr *ngFor="let match of item.matches " (click)="openMatchContent(match,$event)" openMatchContent(match: any,event:any) {} When I try to run this code, I receive an error statin ...

Unusual problem with accessing Object values in vscode using typescript

When attempting to write Object.values in TypeScript, I encounter a visual error (although it compiles without issues). https://example.com/image1.png I have tried searching online and restarting vscode, and here is my current tsconfig.json. https://exa ...

Here is a helpful guide on using the replace() function in JavaScript to swap out specific words within a text that match

My task involves manipulating the following text: const a: string = 'I like orange, blue, black, pink, rose, yellow, white, black'; Along with this string: const b: string =['black', 'yellow']; The objective is to replace ...

Managing the situation where no results are found using React Query

Using react-query, I am fetching data and displaying it on my web page. When the fetched data array is empty, I want to display a message saying that no records are found. If the data array contains items, I map over them to generate cards. However, I ha ...

RXJS: Introducing a functionality in Observable for deferred execution of a function upon subscription

Implementing a Custom Function in Observable for Subscribers (defer) I have created an Observable using event streams, specifically Bluetooth notifications. My goal is to execute a function (startNotifictions) only when the Observable has a subscriber. ...