TypeScript - Functionally Speaking

When defining a function type, the example below does not allow the use of const

interface Square{
    readonly color: string;
    readonly area: number;
}

interface compareTo{
    (const v1: Square, const v2: Square): number;  // syntax error      
}

Is there a way to compare v1 and v2 without altering the object that Square is pointing to?

Answer №1

Declaring this would be ineffective as const in TypeScript does not signify immutability. It only pertains to bindings, and a function parameter is not an externally-visible binding.

Answer №2

Explained in another response, the use of const in ES6 does not prevent objects from being modified, but rather only stops reassignments.

To globally prohibit parameter reassignments, one can employ TSLint's no-parameter-reassignment rule.

If the goal is to prevent object modifications during runtime, one should utilize Object.freeze. At compile time, this restriction can be imposed using the Readonly mapped type. However, if the types are compatible, this method will not have any effect:

interface compareTo {
    (v1: Readonly<Square>, v2: Readonly<Square>): number;      
}
const foo: compareTo = (a: Square, b: Square) => {
  a.area = 0;
  return 1;
}   

Typically, it is not the role of an interface to dictate how a function functions internally; it simply defines its interface. Therefore, it would be represented as follows:

interface compareTo {
    (v1: Square, v2: Square): number;      
}
const foo: compareTo = (a: Readonly<Square>, b: Readonly<Square>) => {
  a.area = 0; // error
  return 1;
}   

This approach will succeed when types are inferred from a generic type, meaning that the type of a is not specified in the implementation of compareTo:

interface compareTo<T = Readonly<Square>> {
    (v1: T, v2: T): number;      
}

const foo: compareTo = (a, b) => {
  a.area = 0; // error
  return 1;
}   

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

Using agSelectCellEditor to populate Angular Grid dropdowns with values from a database

Utilizing refData and agSelectCellEditor in Angular 8 to display dropdown values during editing. I found a solution at the following link: https://www.ag-grid.com/javascript-grid-reference-data/ However, the dropdown list data is fetched from the Databas ...

Setting up a connection between two distinct interfaces without combining them in Typescript

As a newcomer to typescript, imagine having the following scenario: class Foo{ options: fooOptionsObj; constructor(options: fooOptionsObj){ this.options = options; } sayMessage(){ console.log(`I am number${this.options.position}, and I sa ...

A guide to building a versatile component using Ionic 3 and Angular 4

I decided to implement a reusable header for my app. Here's how I went about it: First, I created the component (app-header): app-header.ts: import { Component } from '@angular/core'; @Component({ selector: 'app-header', te ...

Attempting to change the id property into a Mongoose ObjectId

Here is a snippet of my code: acceptContactRequest: async ( _: any, { userId }: IUserInfo, context: ExpressContext ) => {.....} The interface IUserInfo looks like this: export interface IUserInfo { username: string; password: ...

What is preventing me from generating Face3 in my ThreeJS Typescript project

Currently, I'm in the process of generating a Mesh using Face3 within a TypeScript project that utilizes Three.js. However, I've encountered a few issues along the way. const points = [ new Face3(-1, 1, -1),//c new Face3(-1, -1, 1),//b ...

execute protractor test without the need for "webdriver-manager start"

Is there a way to execute protractor tests without having to manually type "webdriver-manager start" in the command line? How can I incorporate "webdriver-manager start" into my code when writing in TypeScript? ...

Tips for verifying the response and status code in Angular 8 while uploading a file to an S3 Presigned URL and receiving a statusCode of 200

Looking to Upload a File: // Using the pre-signed URL to upload the file const httpOptions = { headers: new HttpHeaders({ 'Content-Disposition': 'attachment;filename=' + file.name + '', observe: 'response' }) }; ...

Resizing inputs in Ionic 2 alert boxes

Hello all! I am currently working with the Ionic 2 framework and could use some assistance. I am attempting to make alert inputs that are multi-line or use textareas instead of single line inputs. Any guidance on how to achieve this would be greatly appr ...

Utilize NodeJS and Typescript to input data into a postgreSQL database

Here is my code snippet: signup.post('/signup', urlendcodedParser, async(req: Request, res: Response) => { const username = req.body.username; const password = req.body.password; const age = req.body.age; const email = req ...

Error message displaying Angular Service not able to be injected into component: StaticInjectorError in AppModule

I'm currently attempting to inject a SpotifyService service into a SearchComponent component, where the service requires Http as a parameter. Below is my module setup: @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule ], decla ...

Place two buttons next to each other on the same row

Is there a way to align Native Base buttons so they both appear on the same line? Currently, the second button is positioned correctly on the right, but it seems slightly lower than the first button. How can I adjust this alignment? <View sty ...

Creating an index signature in TypeScript without having to use union types for the values - a comprehensive guide

Is it possible to define an index signature with strict type constraints in TypeScript? interface Foo { [index: string]: number | string } However, I require the value type to be either number or string specifically, not a union of both types (number | ...

The CastError occurred because the attempt to add a string value to an array failed when converting it to a string

An issue I am encountering: *CastError: Cast to string failed for value "[ 'ZTM', 'NASA' ]" (type Array) at path "customers" at model.Query.exec (/Users/mike/Documents/NodeJS-applications/NASA-project/server/node_modules/mongoose/lib/qu ...

The element is assumed to have an 'any' type due to the index expression not being of type 'number'. - Error in Index Signature

I've recently started using TypeScript and encountered the following issue: Element implicitly has an 'any' type because index expression is not of type 'number' This error message appears on this line --> const { status, msg ...

Dynamic tag names can be utilized with ref in TypeScript

In my current setup, I have a component with a dynamic tag name that can either be div or fieldset, based on the value of the group prop returned from our useForm hook. const FormGroup = React.forwardRef< HTMLFieldSetElement | HTMLDivElement, React. ...

Server request successful, but CORS error occurs in browser

When I make an HTTP POST request to the Microsoft login in order to obtain an access token for use with the mail API, the request is successful but my code still goes to the error clause. requestAccessToken(code: string) { console.log("Requesting access t ...

Exploring Angular 5's *ngFor directive with an array of objects

Here is the data I am working with: Initial set of data: var input = [ {ru: "R201", area: "211", unit: "211"}, {ru: "R201", area: "212", unit: "NONE"}, {ru: "R201", area: "HCC", unit: "NONE"}]; Desired result data: var result = [ {area: ...

Which is the superior option: Angular Services or the Typescript Singleton Approach?

How do Angular Singletons compare to TS Singleton patterns? What are the advantages of using Angular's injection over traditional patterns? ...

Error message in Node v12: "The defined module is not properly exported."

When trying to export a function in my index.js file, I encountered an error while running node index.js: module.exports = { ^ ReferenceError: module is not defined Is there a different method for exporting in Node version 12? ...

An application using NodeJS and ExpressJS is experiencing timeout issues when running with TAP testing

Currently, I am conducting tests on an ExpressJS (4.17.8) and NodeJS (16.3) powered server (app) using tap, followed by supertest. The initial focus is on testing the server instantiation, then moving on to its routes. To facilitate this process, my app i ...