typescript generates a declaration file with the private field in a dts file

It makes the type “nominal” so that other types which expose the same public members are not seen as compatible with a type that has a private field. One case where this matters is if you have code like this:

class C {
    #foo = "hello";
    bar = 123;

    static log(instance: C) {
        console.log("foo = ", instance.#foo, " bar = ", instance.bar);

I’m sure there are more examples, but this static method is just one that came to my head.

This C.log function requires an actual instance of the C class since it accesses a private-named instance field on the instance parameter. If the declaration emit doesn’t reflect that the C type is nominal by indicating that it has an ES private field and instead only emits the public fields, the compiler will use structural type comparisons here and won’t produce the expected type errors. For example, that declaration emit would allow dependent code to pass in { bar: 456 } to C.log without any compiler error.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top