What does the typeof keyword return when used with a variable in Typescript?

In TypeScript, a class can be defined as shown below:

class Sup {

    static member: any;
    static log() {
         console.log('sup');
    }
}

If you write the following code:

let x = Sup; 

Why does the type of x show up as typeof Sup (highlighted in vscode) and what does typeof Sup mean? Is it related to the typeof operator?

Moreover, how would you type something like let y = Object.create(Sup)? Is it correctly typed as

let y: typeof Sup = Object.create(Sup)
?

Answer №1

typeof in TypeScript has a unique definition compared to regular JavaScript. It serves as an operator for determining the type of an entity within the value space.

let person = { name: 'bob', age: 26 }

type Person = typeof person // Person is { name: string, age: number }

// These declarations are all the same
let personRef1: { name: string, age: number } = person
let personRef2: typeof person = person
let personRef3: Person = person
let personRef4 = person

// additional examples
let secret = 'helloworld'
type Secret = typeof secret // string

let key = 123
type Key = typeof key // number

let add = (a: number, b: number) => a + b
type Add = typeof add // (a: number, b: number) => number

When assigning SomeClass to a variable, the variable's type becomes typeof SomeClass. The format remains unchanged, unlike other examples, due to the ambiguity involved in simplifying class types; it stays as typeof SomeClass for clarity.

Answer №2

When encountering the statement let x = Sup; in your scenario, it essentially means that variable x is capable of storing the constructor function Sup, rather than an actual instance of it:

class Sup { }

let x: typeof Sup;

x = Sup;       // acceptable
x = new Sup(); // not valid 

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

Steps to displaying a genuine Docx file within a Material CardMedia

Currently, I am facing an issue with positioning a docx file in my app. Interestingly, jpg and mp4 files are displaying correctly, but the docx file is not positioned as expected. If you want to try it out, simply open a doxc file. In the FileContentRend ...

Having trouble properly refreshing Bootstrap scrollspy that is spying on the <body> element

I've been looking at a post on Bootstrap's scrollspy component (found here). In my code, I initialize a new scrollspy to track the body element using: $("body").scrollspy({ offset: 25 }); As my code progresses, I make AJAX requests that add or ...

Running npm start in a React development environment on Linux without automatically opening a browser can be achieved by configuring

As I dive into learning React, I've noticed that I keep running npm start in the terminal multiple times. However, it can be quite frustrating how a new browser window opens each time. I'm currently attempting to prevent this from occurring on my ...

Implementing alphabetical pagination in PHP

I am trying to implement alphabetical pagination in php, but I am facing a problem. When I click on any alphabet, the selected alphabet shows up in the address bar, however, the data starting from the selected alphabet is not displayed. Here are my databa ...

What is the best way to navigate to a specific ID on the homepage using a navigation button on another page?

When a navigation button is clicked on any page other than the home page, I want the home page to load first and then scroll to the corresponding id mentioned in the navlink. Below is the code snippet: <Col sm={5}> <Nav className=& ...

Is it possible for TypeScript to manage a dynamic return type that is not determined by a function parameter?

I am facing a challenge with dynamic type checking using a param type and seeking help to solve it. Even though it might be a difficult task, any assistance would be greatly appreciated! Consider the following code: class DefaultClass { defaultProp: n ...

Exploring the functionality of Next.js with Links and routes

Currently, I am facing an issue with the popover menu in my header that displays products. The problem arises when I click on a product in the list; it navigates correctly to the path "products/some-product" regardless of the selected item. However, if I a ...

Retrieve specific components of objects using a GET request

When visitors land on my web app's homepage, a GET request is triggered to fetch a current list of Stadiums stored in the database through my API. However, the Stadium objects retrieved are packed with unnecessary data, particularly extensive arrays o ...

Error message: Invalid credentials for Twitter API authentication

My attempts to post a tweet seem to be failing for some reason. I suspect that the issue might be related to the signature string, but from following Twitter's instructions on signing requests, everything appears correct. Here is the code snippet I ...

Effortlessly bring in Typescript namespace from specific namespace/type NPM package within a mono-repository

Instead of repeatedly copying Typescript types from one project to another, I have created a private NPM package with all the shared types under a Typescript namespace. Each project installs this NPM package if it uses the shared types. index.d.ts export ...

What could be the reason for my code generating the error [$http:badreq]?

I'm currently attempting to retrieve JSON data from a certain URL and am having trouble getting it to work. Despite going through the Angular documentation and other resources, I still can't pinpoint the issue due to my limited experience with An ...

Sophisticated Sidebar Design using Bootstrap 5

Looking to design a responsive sidebar for navigation on my page, with selected and hover properties. Visualizing the selected option to appear like this: Selected (active) option in sidebar The goal is to have the image cover the left side of the backgr ...

Modifying state within reducers is not allowed

Encountered the following error while using @ngrx/store: index.js?4b23:19 State mutation is prohibited inside of reducers. (anonymous) @ index.js?4b23:19 (anonymous) @ index.ts:54 rootReducer @ index.ts:70 _initialStateFactory @ ng2.ts?2a33:24 AppModule ...

Encountered an issue in Angular 6: Unable to access property '0' of undefined

There's an error popping up in the console saying, Cannot read property '0' of undefined, but surprisingly I'm still getting the expected result. Below is my HTML code snippet: <div class="col-md-3"> <div class="slider-prod ...

The functionality of Flatbutton(Input handler) appears to be malfunctioning

I am having trouble with the file uploader from Material-UI. It doesn't seem to be working properly when I try to select a file. Does anyone have any suggestions on how to handle the input from the file selector? <FlatButton icon={< ...

The connections between module dependencies are unable to be resolved

I'm encountering an issue with the npm link command. Here's the scenario: I have two Angular apps - 1) app-core (published locally) 2) app-main The app-core module has the following dependencies (installed via npm): core rxjs z ...

Guide to storing a collection in an object with Java

Before the changes were saved https://i.stack.imgur.com/hjpXa.jpg After the changes were saved https://i.stack.imgur.com/xABzN.jpg @Entity @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Notification { @Id @GeneratedVa ...

Converting RGBA to Hex Color Code with Javascript: A Step-by-Step Guide

I attempted to change the rgba color representation to hexadecimal, but I encountered difficulty in converting the opacity value while successfully converting the remaining colors. Here is the snippet of my code: var colorcode = "rgba(0, 0, 0, 0.74)"; ...

Deduce the Prop Component Type by Examining the Attribute Type

I am facing an issue with a component that requires a `labels` attribute. <Component defaultValue={FURNITURE.BED} labels={[ { value: FURNITURE.BED, text: 'Bed', }, { value: FURNITURE.COUCH, text: 'C ...

Struggling to retrieve the fake JavaScript data for my Vue.js table

I am a beginner in the development field and encountering the following error report while working with Vue.js 3 115:5 error 'vendorTable' is assigned a value but never used no-unused-vars 115:23 error 'Vue' is not defined no- ...