13

I put this in an externs file:

/** @typedef {{english: string, spanish: string}} */
var SpanishNoun;

Then I have javascript:

/**
 * @param {SpanishNoun} n 
 */
exp1.processData3 = function (n) {
    console.log("pd3:", n.english, n.spanish, n['english'], n['spanish']);
}

Which compiles to:

function(a){console.log("pd3:",a.a,a.c,a.english,a.spanish)};

So it still renamed 'english' to 'a', etc. How do you stop that? Why does it think it can rename something that is "extern".

Rob

Follow-up Question

John's answer led to another question: Can I tell the Closure compiler to, for specific types only, stop renaming properties?

Community
  • 1
  • 1
Rob N
  • 15,024
  • 17
  • 92
  • 165

1 Answers1

5

typedefs don't participate in the renaming calculation

This type definition will:

/** @interface */
function SpanishNoun() {}
/** @type {string} */
SpanishNoun.prototype.english;
/** @type {string} */
SpanishNoun.prototype.spanish;
John
  • 5,443
  • 15
  • 21
  • 1
    I tried this, and it works, but not the way I expected. It causes *all* properties named 'english' and 'spanish' to not be renamed, throughout the code, even if they are on an unrelated type. That doesn't seem right. Is there a way to stop that? I may post this as a separate, followup question. – Rob N Nov 20 '11 at 13:16
  • 2
    @Rob N - this is the standard behavior of Closure in order to avoid bugs (you can read the Closure web site to understand why this is necessary). Closure always renames the same property name to the same mangled name. On the flip side, it does not rename all properties (regardless of where) of the same name -- because in essence non-renaming is just renaming to itself. There is a flag that you can turn on the avoid this, but it is experimental only. – Stephen Chung Nov 21 '11 at 04:28
  • You can change the "all properties" aspect of the property renaming by using type based optimizations: https://code.google.com/p/closure-compiler/wiki/ExperimentalTypeBasedPropertyRenaming but you need to be careful that there is a type relation between externs definition and the usage is known to the compiler. In this world can prevent all renaming of a property of a given name by adding an extern definition on Object.prototype. – John Aug 27 '13 at 00:53
  • This has changed in the current releases of the Closure Compiler. Properties are now promoted from record type reference in externs. – John Mar 27 '15 at 15:44
  • @John , can you elaborate your last comment. I tried using --use_types_for_optimization but it still excludes all properties of same name from renaming as faced by Rob – Jim Aug 19 '22 at 11:21
  • @RobN were you able to resolve? – Jim Aug 19 '22 at 11:22