Search code examples
typescriptconstructorkeyof

Keyof different behavior using constructor assignment


I'm experiencing a different behavior of the "keyof" using the constructor assignement...

Here is the code

class Class1 {
constructor(private a: number, private b: string) {
}
method1() {
    console.log("method1");
    }
}

class Class2 {
    a: number;
    b: string;
    constructor() {
    }
    method1() {
        console.log("method1");
    }
}

type Cet1Props = keyof Class1; // "method1"
type Class2Props = keyof Class2; // "a" | "b" | "method1"

I can't understand why is it so, can someone explain me?

Thanks!!


Solution

  • In Class2 they are public (which is the default), wheras in Class1 they are private.

    To make them comparable (i.e. to prove it is nothing to do with the constructor assignment) add the private access modifier to Class2 (or change Class1 to make them public).

    class Class2 {
        private a: number;
        private b: string;
    
        constructor() {
        }
    
        method1() {
            console.log("method1");
        }
    }
    

    If the a and b members are private, you'll get:

    type Class2Props = keyof Class2;  // "method1"