Using Private Properties in TypeScript Class (Value Never Used)

53 Views Asked by At

Here is the code I am using:

class ProjectInput {
    private templateElement: HTMLTemplateElement;
    private hostElement: HTMLDivElement;

    constructor() {
        this.templateElement = document.getElementById('project-input')! as HTMLTemplateElement;
        this.hostElement = document.getElementById('app')! as HTMLDivElement;
    }
}

I am receiving this error when I try to compile it:

enter image description here

I am using the properties already in the constructor. If I removed the private modifier, no errors are generated. I still need to declare them as private though.

2

There are 2 best solutions below

1
On BEST ANSWER

You say you are using these variable in the constructor, but you are not. You are declaring them, but not using them. At this time, those variable do seem useless. If you don't plan on using them any further, then they should just be deleted.

0
On

Assign value to variable !== reading value from variable, so you have this error as far as scope is private (so the only way to read them is inside class), and there is no such action.

When you removing private from class props, you declare ability to read prop outside class private scope, so you have no error.

To get rid of this error, you can just define getters.