Skip to content Skip to sidebar Skip to footer

Typescript Generates Declaration D.ts File With `#private;` Field

I have a library, written in Typescript, that is being distributed in 2 files: a compiled ECMAScript-2015 compatible Javascript file index.js and a Typescript declaration file inde

Solution 1:

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:

classC {
    #foo = "hello";
    bar = 123;

    staticlog(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.

Solution 2:

I tried to answer your question but was unable to, then I asked my own question out of curiosity, which was answered by a TypeScript contributor, you can find his answer here: What's the purpose of #private in TypeScript definition files?

To summarize, there are some cases where private fields matter when it comes to the comparison between to types, that's why the #private field appears so that the information "contains private members" is part of the type definition.

Solution 3:

#private syntax is currently a stage-3 proposal for javascript. Once browsers support it then it won't be transpiled by typescript.

Post a Comment for "Typescript Generates Declaration D.ts File With `#private;` Field"