Why does the for..in loop not function properly when executing a script with ts-node?

Check out ./src/repro.ts

class P {
    do() { console.log('d'); }
}

const x = new P();

console.log('for in:');
for (const key in x) {
    console.log(key);
}

I'm using this configuration file ./tsconfig.json to compile it (tried different configurations):

{
    "compilerOptions": {
        "target": "ES6",
        "module": "commonjs",
        "lib": ["ES6"],
        "esModuleInterop": true,
        "noImplicitAny": true,
        "strictNullChecks": true,
        "moduleResolution": "node",
        "sourceMap": false,
        "outDir": "dist",
        "baseUrl": ".",
        "paths": {
            "*": ["node_modules/*", "src/types/*"]
        }
    },
    "include": ["src/**/*"]
}

Execution:

> tsc -v                   
Version 4.3.5
> tsc ./src/repro.ts

Output file ./src/repro.js

var P = /** @class */ (function () {
    function P() {
    }
    P.prototype["do"] = function () { console.log('d'); };
    return P;
}());
var x = new P();
console.log('for in:');
for (var key in x) {
    console.log(key);
}

Running the file:

> node ./src/repro.js
for in:
do

My question is, why does this command not output the method "do":

> ts-node ./src/repro.ts   
for in:

Answer №1

In agreement with @Phil's statement, it is not possible to iterate through the methods of an object using a for..in loop. However, you can utilize Object.getOwnPropertyNames() to obtain an array of the method names and then iterate through them. Here is an example:

class MyClass {
    sayHello() { console.log('Hello'); }
}

const obj = new MyClass();

// Displaying the properties
for (const property in obj) {
    console.log(property);
}

// Displaying the method names
for (const method of Object.getOwnPropertyNames(obj.__proto__)) {
    console.log(method);
}
// ["constructor", "sayHello"]

Remember that the array will also contain the method name for the constructor function.

Answer №2

One error I quickly realized was when I ran the following command: tsc ./src/repro.ts. Compiling just one file with tsc without utilizing tsconfig.json resulted in generating pre ES6 code without classes and methods, causing issues with the for..in function.

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

How can you connect a jQuery UI sortable component to an array?

Is there a way to connect a jQuery UI sortable element with an array in order to assign an index to each sortable element within the array? I am looking for a method to automatically sort the array based on the movement of the sortable elements. Any sugg ...

A more concise approach to accessing a generic class method in Typescript

Let's analyze the code snippet below: export class BaseClass<T> { property = this.buildProperty(); buildProperty(){ return someBuilder<T>(); } } Through TypeScript, the type of property is automatically determined based on the ...

I need help figuring out how to set the country code as uneditable and also display a placeholder in react-phone-input-2 with React

How can I display the placeholder after the country code without allowing it to be edited? Currently, it's not showing up in my React functional components. Here is the code snippet: <PhoneInput className="inputTextDirLeft" ...

Error in custom TypeScript: Incorrect error instance detected within the component

I encountered a unique issue with my custom Error export class CustomError extends Error{ constructor(message: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); this.name = "CustomError"; } Furthermore ...

The possibility exists that the onClick function may be null

I am encountering an issue with a props function that is showing an error message stating that the object may be null. import {Dropdown} from "react-bootstrap"; interface GenreButtonProps { key: number; id: number | null; genre: strin ...

Identifying the pressing of the enter key in an input field

Currently, I am developing an innovative IFrame browser that features an omnibox (identified as "address") and a "GO" button (identified as "submit"). One of the key challenges I'm facing is detecting when the user inputs information and hits the Ente ...

Understanding the process of reading cookies on the Angular2 side that have been set by the C# server

I'm struggling to understand how the angular code can access the cookie that was set on the server side. I found the following code snippet on GitHub. This C# function sets the cookie in the Response object with the last line of code. My question is, ...

Unable to establish a connection between the HTML element and the TypeScript variable

I'm facing an issue with my code where the function that worked perfectly for register and login is not functioning properly on the index page. Even though there seems to be no errors in the login and register functions, I have a form with an input s ...

Exploring the Functionality of Using Multiple Middlewares in Vue.js 3

For my web app project using vue.js 3 and vue-router, I followed a helpful tutorial on implementing middleware pipelines. The tutorial can be found at: https://blog.logrocket.com/vue-middleware-pipelines/. This tutorial demonstrated creating middleware to ...

Tips for dynamically displaying a Material UI dialog with smooth fade effects

I am currently developing a basic application that lists users. Whenever I click on a user, I want to display a dialog box with specific information about that user. I have attempted to achieve this using Material UI's Dialog component in different wa ...

Choosing a single radio button value within a nested ng-repeat loop in AngularJS

Help needed with selecting only one radio button value in nested ng-repeat. Please review the source code and suggest any potential mistakes. <form ng-submit="save()"> <div ng-repeat="x in surveyLst"> <div class="row"> < ...

Find the variance between today's date and a selected date, then initiate the timer based on this variance

I have a grid containing data. I utilize the loadGrid() function to preload data or conditions before the grid finishes loading. When the active state is set to 1, my intention is to initiate a timer by calculating the difference between the current date ...

Revamp the current webpage to display attribute values in textual format

As I peruse a webpage, I notice that there is room for improvement in terms of user-friendliness. The page is filled with a list of movie titles, each accompanied by a link to IMDb. However, the IMDB user rating is only visible when hovering over the titl ...

Prevent the <a> tag href attribute from functioning with jQuery

I came across this code snippet: <script type="text/javascript"> $(document).ready(function() { $("#thang").load("http://www.yahoo.com"); $(".SmoothLink").click( function() { $("#thang").fadeOut(); $("#thang").load( ...

Using jquery to dynamically change audio source on click

Is there a way to dynamically change the audio src using jquery? <audio id="audio" controls="" > <source src="" type="audio/mpeg" /> </audio> <ul id="playlist"> <?php if($lists) { foreach ($lists as $list) { ?> ...

Tips for hiding a popover in Angular when clicking outside of it

In a demo I created, rows are dynamically added when the user presses an "Add" button and fills in a name in an input field. Upon clicking "OK," a row is generated with a Star icon that should display a popover when clicked. While I have successfully imple ...

What is the best way to implement a comprehensive switch case in Typescript using string enums that are referencing other string enums?

I am faced with a challenge where I have a subset of values from one enum that I need to switch case across in TypeScript. Here's an example to illustrate my dilemma: const enum Fruit { APPLE = 'Apple', BANANA = 'Banana', ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

How to access parent slider variables in an Angular component

I've developed a slider as the parent component with multiple child components. See the demo here: https://stackblitz.com/edit/angular-ivy-gcgxgh?file=src/app/slide2/slide2.component.html Slider in the parent component: <ng-container *ngFor=&quo ...

Learning Angular2: What is the mechanism behind the automatic incrementation of the ID variable in this particular section?

In This specific part of the Angular2 Tutorial there is a feature that allows users to add new items to an array. Somehow, when the item is added, the ID is automatically incremented but the exact process behind this automation remains a mystery. I am awa ...