HoriSun / closure-compiler

Automatically exported from code.google.com/p/closure-compiler
0 stars 0 forks source link

Add anotation for providing type bindings for templated types #1235

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
The templated type system generally picks the correct type for a template type, 
but at times is unable to and so manually specifying the expected type could be 
useful. Consider the following program that creates a map of uniform value 
types from a map of mixed value types where there is a well defined 
relationship between the types, to a map of uniform value types.

/**
 * @param {V} value
 * @constructor
 * @template V 
 */
var Box = function(value) {};

/**
 * @constructor
 * @template K, V
 */
var Map = function() {};

/**
 * @param {!Map.<K, (!V | !Box.<!V>)>} inMap
 * @constructor
 * @extends Map.<K, V>
 * @template K, V
 */
var WrappedMap = function(inMap){};

/** @type {!Map.<string, (boolean |!Box.<boolean>)>} */
var inMap = new Map();

/** @type {!Map.<string, boolean>} */
var testMap = new WrappedMap(inMap);

This gives the error
input0:26: WARNING - initializing variable
found   : WrappedMap.<string,(Box.<boolean>|boolean)>
required: Map.<string,boolean>
var testMap = new WrappedMap(inMap);
              ^

This is because the compiler has bound V for the newly constructed to (boolean 
| !Box.<boolean>) as the union of possible values for the type of V instead of 
boolean, the intended value. Both bindings are correct in different situations, 
and possibly additional rules could be used to disambiguate, but it would also 
be simple to add a cast-like syntax that would solve the problem in a way 
similar to how Java solves the problem. For example the last line would become

/** @type {!Map.<string, boolean>} */
var testMap = /* @templateTypes string, boolean */ (new WrappedMap(inMap));

Original issue reported on code.google.com by omerkl...@google.com on 12 Feb 2014 at 7:32

GoogleCodeExporter commented 9 years ago
Yeah, we should probably have some notation like that. Anyone, feel free to 
jump in and propose an appropriate syntax.

Original comment by dim...@google.com on 13 Feb 2014 at 12:34

GoogleCodeExporter commented 9 years ago
Maybe:

   /** 
     * @template T
     * @return {Array.<T>}
     */
   function fn() { return [] }

   fn /** @template {string} */(); 

Original comment by concavel...@gmail.com on 3 Mar 2014 at 6:45

GoogleCodeExporter commented 9 years ago
Issue tracking has been migrated to github. Please make any further comments on 
this issue through https://github.com/google/closure-compiler/issues

Original comment by blic...@google.com on 1 May 2014 at 6:31

GoogleCodeExporter commented 9 years ago

Original comment by blic...@google.com on 1 May 2014 at 6:34