Keyof different behavior using constructor assignment

30 Views Asked by At

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!!

1

There are 1 best solutions below

0
On BEST ANSWER

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"