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

前端 未结 3 1838
心在旅途
心在旅途 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题