Mark Hills
unread,Sep 21, 2023, 1:43:50 PM9/21/23Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to closure-comp...@googlegroups.com
I use addEventListener() a lot, and am looking for a concise design
pattern to fulfill good type checking every time.
A simple example is limited to assuming type "Event":
window.addEventListener('error',
event => console.warn(event.error))
Loss of types in the event handler can lead to bugs; in this case it must
assume '.error' is valid.
What is the most concise way to get full type checking?
Below is an attempt at the spirit of what I'm trying to achive.
It's a step in the direct direction, but the longhand JSDoc isn't always
convenient.
But ideally something as concise as this would full check the types:
window.addEventListener('error',
wrap(ErrorEvent, event => console.warn(event.error))
Requires exchanging between run-time and compile-time types, is this even
possible?
Alternatively, something in the compiler itself deepens the understanding
of addEventListener(), to map the given string to corresponding event
type.
--
Mark
window.addEventListener('error', wrap(ErrorEvent, handler));
/**
* @param {!ErrorEvent} event
*/
function handler(event) {
console.log(event.error);
}
/**
* Re-usable wrapper for event handlers
*
* @template CompileTimeType
* @param {!Object} run_time_type
* @param {function(CompileTimeType)} callback
* @return {function(!Event)}
*/
function wrap(run_time_type, callback) {
return go;
/**
* @param {!Event} event
*/
function go(event) {
if (!(event instanceof run_time_type))
throw new Error(`An unexpected event type arrived`);
callback(event);
}
}