What is the syntax for using typeof with anonymous types in TypeScript?

After reading an article, I'm still trying to grasp the concept of using typeof in TypeScript for real-world applications. I understand it's related to anonymous types, but could someone provide a practical example of how it can be used?

Appreciate any insights you can offer!

For reference, here's a snippet of code from the aforementioned article.

let rectangle1 = { width: 100, height: 200 };

// Get the type of `rectangle1` and name it `Rectangle`
type Rectangle = typeof rectangle1;

let rectangle2: Rectangle;

Answer №1

There are numerous scenarios where this can be applied.

For instance, in a situation where the object is already defined as an object literal, and there is no need to explicitly define its type but you still want to pass it around in a type-safe manner to methods:

let rectangle1 = { width: 100, height: 200 };
type Rectangle = typeof rectangle1;
function clone (r: Rectangle ): Rectangle {
    return  r;
}

Alternatively, when a variable or function is exported by a module but is not publicly exposed, using typeof allows for creating a named type for the variable. For example, it was utilized in this answer

import * as ts from 'typescript' // Import will be elided as long as we only use types from it, so we don't have the compiler code loaded at runtime

type CompilerOptions = typeof ts.parseCommandLine extends (...args: any[])=> infer TResult ? 
    TResult extends { options: infer TOptions } ? TOptions : never : never;
type TypeAcquisition = typeof ts.parseCommandLine extends (...args: any[])=> infer TResult ? 
    TResult extends { typeAcquisition?: infer TTypeAcquisition } ? TTypeAcquisition : never : never;

typeof can also be used without a named type. For instance, defining the type of a parameter to be the same as another parameter's type helps avoid redundant typing, especially for lengthy types.

function asPromise(value: string| number| Date) : Promise<typeof value> { return null as any; }

The possibilities are endless, these are just a few examples.

Answer №2

Suppose you need to ensure that only the correct type is passed to a filter function, you can utilize the following code snippet.

const equalFunction:Operator = (value: string, filterValue: string) => {
  return value == filterValue;
};

const startsWithFunction:Operator = (value: string, filterValue: string) => {
  return value.startsWith(filterValue);
};

const containsFunction:Operator =(value: string, filterValue: string) => {
  return !!value.match(filterValue);
};

const endsWithFunction:Operator = (value:string, filterValue: string) => {
  return value.endsWith(filterValue);
};

const regexFunction:Operator = (value: string, filterValue: RegExp) => {
  return filterValue.test(value);
};

const StringOperatorsMap = {
  //equal
  '=': equalFunction,
  'eq':equalFunction,
  'equals':equalFunction,
  //contains
  'contains':containsFunction,
  '*':containsFunction,
  //regex
  'regex':regexFunction,
  'match':regexFunction,
  're':regexFunction,
  //startsWith
  'startsWith':startsWithFunction,
  '^':startsWithFunction,
  //endsWith
  'endsWith':endsWithFunction,
  '$':endsWithFunction
};

export type StringOperators = keyof typeof StringOperatorsMap;
export const getOperator = (operator: StringOperators) => {
  return StringOperatorsMap[operator];
};

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

Mastering Angular 7: A guide to efficiently binding values to radio buttons

Struggling to incorporate radio buttons into my project, I encountered an issue where the first radio button couldn't be checked programmatically. Despite attempting the suggested Solution, it didn't resolve the problem within my code. Below is ...

The type 'undefined' cannot be assigned to type 'CartItem'

While running my program, I encountered the error 'Type 'undefined' is not assignable to type 'CartItem'. Unfortunately, I am unable to resolve this issue :(. import { Injectable } from '@angular/core'; import { CartItem ...

Bringing together the functionality of tap to dismiss keyboard, keyboard avoiding view, and a submit button

On my screen, there's a big image along with a text input and a button at the bottom. The screen has three main requirements: When the user taps on the input, both the input and button should be visible above the keyboard The user must be able to ta ...

Angular Error: The first argument has a property that contains NaN

Struggling with a calculation formula to find the percentage using Angular and Typescript with Angularfire for database storage. Encountered an error stating First argument contains NaN in property 'percent.percentKey.percentMale. The properties are d ...

Utilizing TypeScript Modules for Enhanced Ambient Environments in Node.js

Currently, I am working on creating an ambient module in node.js by utilizing the Visual Studio developer tools. This is what the module code structure looks like: module "Module" { export class Class { first = "First"; second = "Second" ...

Error: React is throwing a SyntaxError because a ")" is missing in the argument list

While working on a React-typescript project using Vite, I encountered an issue where my page was displaying blank and showing the error : Uncaught SyntaxError: missing ) after argument list (at main.tsx:6:51) This error was found in the main.tsx file : im ...

Differences between Typescript compilation: Using dot notation vs square brackets when accessing non-existent properties

Imagine having the given class and code snippet: class myClass{ x: number; } const obj = new myClass(); obj.y = 7; // produces a compile error. Property 'y' does not exist on type myClass. obj['y'] = 7; // compiles without any issu ...

Is it possible to swap out the Firestore module `doc` with the `document` module

I enjoy using the Firebase version 9 modules, however, I find that doc is not to my liking. It would be better if it were document, similar to how collection is not shortened to col. The following code does not function as expected: import { doc, collecti ...

Is it possible to implement drag and drop functionality for uploading .ply, .stl, and .obj files in an angular application?

One problem I'm facing is uploading 3D models in angular, specifically files with the extensions .ply, .stl, and .obj. The ng2-upload plugin I'm currently using for drag'n'drop doesn't support these file types. When I upload a file ...

Best method for integrating widget scripts in Angular 5

I am in the process of developing an Angular 5 application and I have encountered a challenge while trying to integrate a widget into one of the components. Following the guidance provided in this particular question, I attempted to add the widget as inst ...

Leveraging keyboard input for authentication in Angular

Would it be possible to modify a button so that instead of just clicking on it, users could also enter a secret passphrase on the keyboard to navigate to the next page in Angular? For example, typing "nextpage" would take them to the next page. If you&apo ...

Typescript and MomentJS integration - What is the data type of the moment() function?

Currently in the process of upgrading my project from ES5 to ES6, I've encountered a problem with MomentJS (version 2.18.1). The issue arises when dealing with variables that are Moment objects and the inability to call moment() on them. For instance ...

Displaying Information in Angular Modal Windows

I'm facing an issue while trying to create an edit button for a formGroup that is initially saved. When the user clicks on the adjacent button, a modal should open with editable data. However, I encountered this error and haven't been able to res ...

The Angular Http Interceptor is failing to trigger a new request after refreshing the token

In my project, I implemented an HTTP interceptor that manages access token refreshing. If a user's access token expires and the request receives a 401 error, this function is designed to handle the situation by refreshing the token and re-executing ...

Mastering the proper implementation of observables, async/await, and subscribing in Angular

I have a JSON file located at assets/constants/props.json. Inside this file, there is a key called someValue with the value of abc. The structure of the JSON file can be seen in the following image: https://i.stack.imgur.com/MBOP4.jpg I also have a serv ...

Angular 2 Routing 3.0: Paying Attention to Letter Case

let routesList: Routes = [ { path: 'x', component: xComponent }, { path: 'y', component: yComponent }, { path: 'zComponent', component: zComponent } ]; When entering "x" in the URL, it navigates to the component page. Ho ...

Navigating the waters of importing npm modules with typescript, gulp, and browserify is a skill

I'm facing challenges with performing some fundamental tasks such as importing packages that I installed using NPM. Despite conducting extensive research online and following various tutorials, I have been unable to achieve success. Here is my current ...

Filter the array while maintaining its current structure

I'm struggling to create an array filter that can handle exact and partial data within a nested array structure. The challenge is maintaining the integrity of the top-level structure while filtering based on data in the second layer. Here's an ex ...

Typescript's identification of a dispute between RequireJS and NodeJS definitions

I obtained the Typescript RequireJS definition from Definitely Typed. It includes an ambient declaration of Require that clashes with the NodeJs command "require". See below for the declaration and the error message: Declaration: declare var require: Req ...

Using React MUI to implement a custom Theme attribute within a component

I have a CircularProgress element that I want to center, and to make the styling reusable, I decided to create a theme.d.ts file: import { Theme, ThemeOptions } from '@mui/material/styles' declare module '@mui/material/styles' { inte ...