Typescript generates declaration d.ts file with `#private;` field

前端 未结 3 1811
心在旅途
心在旅途 2021-01-12 13:08

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 d

相关标签:
3条回答
  • 2021-01-12 13:33

    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.

    0 讨论(0)
  • 2021-01-12 13:33

    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.

    0 讨论(0)
  • 2021-01-12 13:35

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

    0 讨论(0)
提交回复
热议问题