Search code examples
javascripttypescriptfor-in-loopts-node

Why for..in do not work when I run script with ts-node?


Here's ./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 compiling it using this ./tsconfig.json (also tried without config at all, or with ES2019 target and lib):

{
    "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/**/*"]
}

Like this:

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

Which produces this ./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);
}

And I run it (the same for node v10,12,14,16):

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

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

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

Solution

  • As @Phil said, you can't iterate through the methods of an object using for..in, but you can use Object.getOwnPropertyNames() to give you an array of the methods names and iterate through it so you could do:

    class P {
        do() { console.log('d'); }
    }
    
    const x = new P();
    
    // Logs your properties
    for (const key in x) {
        console.log(key);
    }
    
    // Logs your methods names
    for (const key of Object.getOwnPropertyNames(x.__proto__) {
        console.log(key);
    }
    // ["constructor", "do"]
    

    Keep in mind that array will also include the constructor method name.