Utilize variable as both a function and an instance of a class

Is there a way to access a variable as both a function and an object instance using TypeScript?

log("something");

log.info("something");

I've attempted various methods, such as modifying the prototype, but nothing has proven successful so far:

var log = (...args) => {
   console.log(...args);
};

log.prototype.info = (...args) => console.info(...args);

Answer №1

Utilizing Object.assign makes this task achievable.

type Log = {
    (...args: any): void;
    info: (...args: any) => void;
};

const log: Log = Object.assign((...args: any) => console.log(...args), {
    info: (...args: any) => console.log('INFO:', ...args),
});

log('hello');

log.info('world');

Here is the compiled version:

"use strict";
const log = Object.assign((...args) => console.log(...args), {
    info: (...args) => console.log('INFO:', ...args),
});
log('hello');
log.info('world');

If you prefer, there's no need to explicitly define the Log type. TypeScript will deduce the types of objects passed to Object.assign and create an intersection between them automatically.

const log = Object.assign((...args: any) => console.log(...args), {
    info: (...args: any) => console.log('INFO:', ...args),
});

log('hello');

log.info('world');

Answer №2

You have the ability to add an .info property to the function object that was assigned to log in basic JavaScript.

log = (...args) => console.log(...args);
log.info = (...args) => console.info(...args);

log("something");
log.info("something");

If you are working with TypeScript, make sure to qualify as needed, or use : any[]

const log = (...args: any[]) => console.log(...args);
log.info = (...args: any[]) => console.info(...args);
log("something");
log.info("something");

Credit to @HereticMonkey for sharing the TS Playground link. Please note: the console.info message will only display in the developer tools, not in the TS playground's in-page log.

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

Converting base64 dataUrls into images using typescript

When using ng2-image cropper, it does not accept the "src" attribute and instead requires the "image" attribute. As a result, if a dataUrl is provided, the image will not display in the cropper. I am utilizing the camera to capture an image and obtaining ...

What are the steps to start a project on a personal computer?

Utilized on   - Windows 7, 64-bit I am interested in exploring how the project functions with github.com - project. Query: How can I get the project to do this? Steps Taken:   1. Saved the project to the directory. c:\test\visualStudio ...

How can I efficiently transfer information between AngularJS modules?

Angular offers the flexibility of creating independent Modules that can be reused in various parts of your application. Imagine having a module dedicated to managing lists, which you want to use across your entire application and populate in different ways ...

Check out the new Bootstrap 5 form when it's successfully validated

I need to execute some JavaScript if my form is valid. I am using Bootstrap 5 and found this code, but I am unsure how to add 'if form.is_valid {}' <script> (function () { 'use strict' const forms = document.querySelectorAll(&apos ...

Ways to include x-api-key in Angular API request headers

I am attempting to include the x-api-key header in the headers, as shown below: service.ts import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; import { Observable } from ...

Gather data from a variety of HTML5 video seminars

I am encountering an issue where I have multiple videos and I want to receive events from each of them. However, I am only able to get the event from one video (as tested in Chrome). Why is this happening? Here is the HTML code: <video id="video1" pre ...

Unable to globally install @angular/cli using Node.js on Red Hat software collection

After installing node.js 8 from Red Hat Software Collection (rh-nodejs8), I encountered an issue where I couldn't globally install TypeScript or @Angular/CLI because my bash session was restricted by scl-utils, requiring admin rights for global instal ...

Comparing Input and Output Event Binding

Can you provide reasons why using @Output for events is more advantageous than passing an @Input function in Angular 2+? Utilizing @Input: Parent Template: <my-component [customEventFunction]=myFunction></my-component> Inside parent-compone ...

Exploring the power of Vue3 with Shadow DOM in web components

I've been experimenting with web components using Vue3 and I'm curious about how the Shadow DOM works. I encountered an issue where a third party library was trying to access elements using getElementById() and it was throwing an error because th ...

What is the process for sending a JSON response and then redirecting to an HTML page after a successful event in Node.js using Express?

Trying to send a JSON response and redirect the page simultaneously in Express.js. Need help figuring out how to achieve this. Is it possible to redirect in Express.js while sending a JSON response to the client? The goal is to use this JSON data to render ...

Center the text vertically within a card using Vuetify styling

I am seeking a way to vertically align text within a card using Vuetify or traditional CSS in a Vue project. Here is my code: <template> <div> <v-container class="my-5"> <v-row justify="space-between"> <v- ...

Tips on customizing Google Analytics code with Google Tag Manager

My website is currently equipped with the Google Analytics tracking code implemented through Google Tag Manager. The standard Google Analytics code typically appears as follows: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']= ...

How can you debug a Node.js CLI tool using WebStorm?

Struggling to develop a CLI tool using TypeScript within WebStorm as my IDE. No matter what I try, debugging just won't work for me. My journey in Node.js CLI programming started with this tutorial. Successfully transpiling the TS source with npx tsc, ...

When the JSON array is converted into a string, it appears as undefined

Below is a snippet of my service.spec.ts file: service.spec.ts it('should mock the http requests', inject([Service, MockBackend], (service, mockBackend) => { let result:any; mockBackend.connections.subscribe((connection) => { ...

Tips for Retrieving Data from a Multi-Dimensional Array

I need help accessing the values in my array and assigning them to variables for later use. I have created an array and used the randomGo() function to generate a random number that corresponds to a pair of numbers within the array. My goal is to assign ...

Leveraging React's State Values and Props

Can you help me with a React component challenge? I have two components that I need to work with: <select> <mytable> I want to build a new component called <myInterface>. The state of <myInterface>, let's call it S, needs to ...

I am having trouble with the Primeng password template suggestions not appearing as expected

The demonstration available at this link is not functioning correctly, unlike the example provided in the documentation at this website. In the StackBlitz demo, the suggestions are not being displayed as expected for the password template. Take a look at ...

How can you integrate Dygraph into your React project alongside redux?

Lately, I've been facing some challenges while trying to integrate Dygraph into React (utilizing Redux). The Dygraph wrapper packages available on NPM don't seem to cooperate. Furthermore, the conventional method of using: <div id="graph"> ...

Explore the inner workings and file contents of a package using the NPM registry API, by accessing a detailed JSON response

Can the NPM registry API be utilized to access an endpoint like https://registry.npmjs.org/jquery And examine the Tarbells structure and internal files without the need to download the package, in a JSON response similar to: { files: { js: registr ...

Offspring of div should have equal height without the top and bottom padding

Looking to ensure that the height of child divs matches the height of the parent divs. Currently, the divs expand as the page is resized. This is for search results, so there are multiple identical code blocks. function matchHeight() { $result = $(&a ...