Skip to content
This repository was archived by the owner on Feb 26, 2024. It is now read-only.

Commit

Permalink
chore: make type checking stricter
Browse files Browse the repository at this point in the history
  • Loading branch information
mhevery committed Mar 10, 2017
1 parent b09ff8c commit ca7ef1f
Show file tree
Hide file tree
Showing 65 changed files with 431 additions and 394 deletions.
18 changes: 10 additions & 8 deletions lib/browser/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ import {registerElementPatch} from './register-element';
const set = 'set';
const clear = 'clear';
const blockingMethods = ['alert', 'prompt', 'confirm'];
const _global = typeof window === 'object' && window || typeof self === 'object' && self || global;
const _global: any =
typeof window === 'object' && window || typeof self === 'object' && self || global;

patchTimer(_global, set, clear, 'Timeout');
patchTimer(_global, set, clear, 'Interval');
Expand Down Expand Up @@ -64,7 +65,7 @@ function patchXHR(window: any) {
}

function scheduleTask(task: Task) {
self[XHR_SCHEDULED] = false;
(XMLHttpRequest as any)[XHR_SCHEDULED] = false;
const data = <XHROptions>task.data;
// remove existing event listener
const listener = data.target[XHR_LISTENER];
Expand All @@ -75,7 +76,7 @@ function patchXHR(window: any) {
if (data.target.readyState === data.target.DONE) {
// sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
// readyState=4 multiple times, so we need to check task state here
if (!data.aborted && self[XHR_SCHEDULED] && task.state === 'scheduled') {
if (!data.aborted && (XMLHttpRequest as any)[XHR_SCHEDULED] && task.state === 'scheduled') {
task.invoke();
}
}
Expand All @@ -87,7 +88,7 @@ function patchXHR(window: any) {
data.target[XHR_TASK] = task;
}
sendNative.apply(data.target, data.args);
self[XHR_SCHEDULED] = true;
(XMLHttpRequest as any)[XHR_SCHEDULED] = true;
return task;
}

Expand All @@ -101,13 +102,13 @@ function patchXHR(window: any) {
return abortNative.apply(data.target, data.args);
}

const openNative =
const openNative: Function =
patchMethod(window.XMLHttpRequest.prototype, 'open', () => function(self: any, args: any[]) {
self[XHR_SYNC] = args[2] == false;
return openNative.apply(self, args);
});

const sendNative =
const sendNative: Function =
patchMethod(window.XMLHttpRequest.prototype, 'send', () => function(self: any, args: any[]) {
const zone = Zone.current;
if (self[XHR_SYNC]) {
Expand Down Expand Up @@ -162,8 +163,9 @@ function findPromiseRejectionHandler(evtName: string) {
}

if (_global['PromiseRejectionEvent']) {
Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
(Zone as any)[zoneSymbol('unhandledPromiseRejectionHandler')] =
findPromiseRejectionHandler('unhandledrejection');

Zone[zoneSymbol('rejectionHandledHandler')] = findPromiseRejectionHandler('rejectionhandled');
(Zone as any)[zoneSymbol('rejectionHandledHandler')] =
findPromiseRejectionHandler('rejectionhandled');
}
14 changes: 7 additions & 7 deletions lib/browser/define-property.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import {zoneSymbol} from '../common/utils';
* things like redefining `createdCallback` on an element.
*/

const _defineProperty = Object[zoneSymbol('defineProperty')] = Object.defineProperty;
const _getOwnPropertyDescriptor = Object[zoneSymbol('getOwnPropertyDescriptor')] =
const _defineProperty = (Object as any)[zoneSymbol('defineProperty')] = Object.defineProperty;
const _getOwnPropertyDescriptor = (Object as any)[zoneSymbol('getOwnPropertyDescriptor')] =
Object.getOwnPropertyDescriptor;
const _create = Object.create;
const unconfigurablesKey = zoneSymbol('unconfigurables');
Expand All @@ -37,7 +37,7 @@ export function propertyPatch() {
return obj;
};

Object.create = <any>function(obj, proto) {
Object.create = <any>function(obj: any, proto: any) {
if (typeof proto === 'object' && !Object.isFrozen(proto)) {
Object.keys(proto).forEach(function(prop) {
proto[prop] = rewriteDescriptor(obj, prop, proto[prop]);
Expand All @@ -55,17 +55,17 @@ export function propertyPatch() {
};
};

export function _redefineProperty(obj, prop, desc) {
export function _redefineProperty(obj: any, prop: string, desc: any) {
const originalConfigurableFlag = desc.configurable;
desc = rewriteDescriptor(obj, prop, desc);
return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);
};

function isUnconfigurable(obj, prop) {
function isUnconfigurable(obj: any, prop: any) {
return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop];
}

function rewriteDescriptor(obj, prop, desc) {
function rewriteDescriptor(obj: any, prop: string, desc: any) {
desc.configurable = true;
if (!desc.configurable) {
if (!obj[unconfigurablesKey]) {
Expand All @@ -76,7 +76,7 @@ function rewriteDescriptor(obj, prop, desc) {
return desc;
}

function _tryDefineProperty(obj, prop, desc, originalConfigurableFlag) {
function _tryDefineProperty(obj: any, prop: string, desc: any, originalConfigurableFlag: any) {
try {
return _defineProperty(obj, prop, desc);
} catch (error) {
Expand Down
2 changes: 1 addition & 1 deletion lib/browser/event-target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const NO_EVENT_TARGET =
.split(',');
const EVENT_TARGET = 'EventTarget';

export function eventTargetPatch(_global) {
export function eventTargetPatch(_global: any) {
let apis = [];
const isWtf = _global['wtf'];
if (isWtf) {
Expand Down
4 changes: 2 additions & 2 deletions lib/browser/property-descriptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const eventNames =
'copy cut paste abort blur focus canplay canplaythrough change click contextmenu dblclick drag dragend dragenter dragleave dragover dragstart drop durationchange emptied ended input invalid keydown keypress keyup load loadeddata loadedmetadata loadstart message mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup pause play playing progress ratechange reset scroll seeked seeking select show stalled submit suspend timeupdate volumechange waiting mozfullscreenchange mozfullscreenerror mozpointerlockchange mozpointerlockerror error webglcontextrestored webglcontextlost webglcontextcreationerror'
.split(' ');

export function propertyDescriptorPatch(_global) {
export function propertyDescriptorPatch(_global: any) {
if (isNode && !isMix) {
return;
}
Expand Down Expand Up @@ -86,7 +86,7 @@ function patchViaCapturingAllTheEvents() {
const property = eventNames[i];
const onproperty = 'on' + property;
self.addEventListener(property, function(event) {
let elt = <Node>event.target, bound, source;
let elt: any = <Node>event.target, bound, source;
if (elt) {
source = elt.constructor['name'] + '.' + onproperty;
} else {
Expand Down
2 changes: 1 addition & 1 deletion lib/browser/register-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function registerElementPatch(_global: any) {
const callbacks =
['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];

(<any>document).registerElement = function(name, opts) {
(<any>document).registerElement = function(name: any, opts: any) {
if (opts && opts.prototype) {
callbacks.forEach(function(callback) {
const source = 'Document.registerElement::' + callback;
Expand Down
10 changes: 6 additions & 4 deletions lib/browser/webapis-media-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,25 @@
if (!_global['MediaQueryList']) {
return;
}
const patchEventTargetMethods = Zone[Zone['__symbol__']('patchEventTargetMethods')];
const patchEventTargetMethods =
(Zone as any)[(Zone as any)['__symbol__']('patchEventTargetMethods')];
patchEventTargetMethods(
_global['MediaQueryList'].prototype, 'addListener', 'removeListener', (self, args) => {
_global['MediaQueryList'].prototype, 'addListener', 'removeListener',
(self: any, args: any[]) => {
return {
useCapturing: false,
eventName: 'mediaQuery',
handler: args[0],
target: self || _global,
name: 'mediaQuery',
invokeAddFunc: function(addFnSymbol: any, delegate) {
invokeAddFunc: function(addFnSymbol: any, delegate: any) {
if (delegate && (<Task>delegate).invoke) {
return this.target[addFnSymbol]((<Task>delegate).invoke);
} else {
return this.target[addFnSymbol](delegate);
}
},
invokeRemoveFunc: function(removeFnSymbol: any, delegate) {
invokeRemoveFunc: function(removeFnSymbol: any, delegate: any) {
if (delegate && (<Task>delegate).invoke) {
return this.target[removeFnSymbol]((<Task>delegate).invoke);
} else {
Expand Down
2 changes: 1 addition & 1 deletion lib/browser/webapis-notification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
if (!desc || !desc.configurable) {
return;
}
const patchOnProperties = Zone[Zone['__symbol__']('patchOnProperties')];
const patchOnProperties = (Zone as any)[(Zone as any)['__symbol__']('patchOnProperties')];
patchOnProperties(Notification.prototype, null);
}
})(typeof window === 'object' && window || typeof self === 'object' && self || global);
4 changes: 2 additions & 2 deletions lib/browser/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ export function apply(_global: any) {
if (!(<any>_global).EventTarget) {
patchEventTargetMethods(WS.prototype);
}
(<any>_global).WebSocket = function(a, b) {
(<any>_global).WebSocket = function(a: any, b: any) {
const socket = arguments.length > 1 ? new WS(a, b) : new WS(a);
let proxySocket;
let proxySocket: any;

// Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance
const onmessageDesc = Object.getOwnPropertyDescriptor(socket, 'onmessage');
Expand Down
4 changes: 2 additions & 2 deletions lib/common/timers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ interface TimerOptions extends TaskData {
}

export function patchTimer(window: any, setName: string, cancelName: string, nameSuffix: string) {
let setNative = null;
let clearNative = null;
let setNative: Function = null;
let clearNative: Function = null;
setName += nameSuffix;
cancelName += nameSuffix;

Expand Down
24 changes: 13 additions & 11 deletions lib/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
*/

// Hack since TypeScript isn't compiling this for a worker.
declare const WorkerGlobalScope;
declare const WorkerGlobalScope: any;
declare const window: any;

export const zoneSymbol: (name: string) => string = (n) => `__zone_symbol__${n}`;
const _global = typeof window === 'object' && window || typeof self === 'object' && self || global;

Expand All @@ -25,7 +27,7 @@ export function bindArguments(args: any[], source: string): any[] {
return args;
}

export function patchPrototype(prototype, fnNames) {
export function patchPrototype(prototype: any, fnNames: string[]) {
const source = prototype.constructor['name'];
for (let i = 0; i < fnNames.length; i++) {
const name = fnNames[i];
Expand Down Expand Up @@ -55,7 +57,7 @@ export const isMix: boolean = typeof process !== 'undefined' &&
{}.toString.call(process) === '[object process]' && !isWebWorker &&
!!(typeof window !== 'undefined' && window['HTMLElement']);

export function patchProperty(obj, prop) {
export function patchProperty(obj: any, prop: string) {
const desc = Object.getOwnPropertyDescriptor(obj, prop) || {enumerable: true, configurable: true};

const originalDesc = Object.getOwnPropertyDescriptor(obj, 'original' + prop);
Expand All @@ -82,7 +84,7 @@ export function patchProperty(obj, prop) {
}

if (typeof fn === 'function') {
const wrapFn = function(event) {
const wrapFn = function(event: Event) {
let result;
result = fn.apply(this, arguments);

Expand Down Expand Up @@ -365,8 +367,8 @@ export function makeZoneAwareListeners(fnName: string) {
return [];
}
return target[EVENT_TASKS]
.filter(task => task.data.eventName === eventName)
.map(task => task.data.handler);
.filter((task: Task) => (task.data as any)['eventName'] === eventName)
.map((task: Task) => (task.data as any)['handler']);
};
}

Expand All @@ -393,7 +395,7 @@ export function patchEventTargetMethods(
const originalInstanceKey = zoneSymbol('originalInstance');

// wrap some native API on `window`
export function patchClass(className) {
export function patchClass(className: string) {
const OriginalClass = _global[className];
if (!OriginalClass) return;

Expand Down Expand Up @@ -497,7 +499,7 @@ export interface MacroTaskMeta extends TaskData {
// TODO: @JiaLiPassion, support cancel task later if necessary
export function patchMacroTask(
obj: any, funcName: string, metaCreator: (self: any, args: any[]) => MacroTaskMeta) {
let setNative = null;
let setNative: Function = null;

function scheduleTask(task: Task) {
const data = <MacroTaskMeta>task.data;
Expand Down Expand Up @@ -530,7 +532,7 @@ export interface MicroTaskMeta extends TaskData {

export function patchMicroTask(
obj: any, funcName: string, metaCreator: (self: any, args: any[]) => MicroTaskMeta) {
let setNative = null;
let setNative: Function = null;

function scheduleTask(task: Task) {
const data = <MacroTaskMeta>task.data;
Expand Down Expand Up @@ -570,5 +572,5 @@ export function findEventTask(target: any, evtName: string): Task[] {
return result;
}

Zone[zoneSymbol('patchEventTargetMethods')] = patchEventTargetMethods;
Zone[zoneSymbol('patchOnProperties')] = patchOnProperties;
(Zone as any)[zoneSymbol('patchEventTargetMethods')] = patchEventTargetMethods;
(Zone as any)[zoneSymbol('patchOnProperties')] = patchOnProperties;
6 changes: 3 additions & 3 deletions lib/extra/bluebird.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
* found in the LICENSE file at https://angular.io/license
*/
((_global: any) => {
const __symbol__ = Zone['__symbol__'];
const __symbol__ = (Zone as any)['__symbol__'];
// TODO: @JiaLiPassion, we can automatically patch bluebird
// if global.Promise = Bluebird, but sometimes in nodejs,
// global.Promise is not Bluebird, and Bluebird is just be
// used by other libraries such as sequelize, so I think it is
// safe to just expose a method to patch Bluebird explicitly
Zone[__symbol__('bluebird')] = function patchBluebird(Bluebird) {
Bluebird.setScheduler((fn) => {
(Zone as any)[__symbol__('bluebird')] = function patchBluebird(Bluebird: any) {
Bluebird.setScheduler((fn: Function) => {
Zone.current.scheduleMicroTask('bluebird', fn);
});
};
Expand Down
22 changes: 11 additions & 11 deletions lib/jasmine/jasmine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,24 @@

'use strict';
(() => {
const __extends = function(d, b) {
const __extends = function(d: any, b: any) {
for (const p in b)
if (b.hasOwnProperty(p)) d[p] = b[p];
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new (__ as any)());
};
// Patch jasmine's describe/it/beforeEach/afterEach functions so test code always runs
// in a testZone (ProxyZone). (See: angular/zone.js#91 & angular/angular#10503)
if (!Zone) throw new Error('Missing: zone.js');
if (typeof jasmine == 'undefined') throw new Error('Missing: jasmine.js');
if (jasmine['__zone_patch__'])
if ((jasmine as any)['__zone_patch__'])
throw new Error('\'jasmine\' has already been patched with \'Zone\'.');
jasmine['__zone_patch__'] = true;
(jasmine as any)['__zone_patch__'] = true;

const SyncTestZoneSpec: {new (name: string): ZoneSpec} = Zone['SyncTestZoneSpec'];
const ProxyZoneSpec: {new (): ZoneSpec} = Zone['ProxyZoneSpec'];
const SyncTestZoneSpec: {new (name: string): ZoneSpec} = (Zone as any)['SyncTestZoneSpec'];
const ProxyZoneSpec: {new (): ZoneSpec} = (Zone as any)['ProxyZoneSpec'];
if (!SyncTestZoneSpec) throw new Error('Missing: SyncTestZoneSpec');
if (!ProxyZoneSpec) throw new Error('Missing: ProxyZoneSpec');

Expand All @@ -47,7 +47,7 @@
let testProxyZone: Zone = null;

// Monkey patch all of the jasmine DSL so that each function runs in appropriate zone.
const jasmineEnv = jasmine.getEnv();
const jasmineEnv: any = jasmine.getEnv();
['describe', 'xdescribe', 'fdescribe'].forEach((methodName) => {
let originalJasmineFn: Function = jasmineEnv[methodName];
jasmineEnv[methodName] = function(description: string, specDefinitions: Function) {
Expand Down Expand Up @@ -89,7 +89,7 @@
// The `done` callback is only passed through if the function expects at least one argument.
// Note we have to make a function with correct number of arguments, otherwise jasmine will
// think that all functions are sync or async.
return testBody && (testBody.length ? function(done) {
return testBody && (testBody.length ? function(done: Function) {
return testProxyZone.run(testBody, this, [done]);
} : function() {
return testProxyZone.run(testBody, this);
Expand All @@ -101,8 +101,8 @@
interface QueueRunnerAttrs {
queueableFns: {fn: Function}[];
onComplete: () => void;
clearStack: (fn) => void;
onException: (error) => void;
clearStack: (fn: any) => void;
onException: (error: any) => void;
catchException: () => boolean;
userContext: any;
timeout: {setTimeout: Function, clearTimeout: Function};
Expand All @@ -112,7 +112,7 @@
const QueueRunner = (jasmine as any).QueueRunner as {new (attrs: QueueRunnerAttrs): QueueRunner};
(jasmine as any).QueueRunner = (function(_super) {
__extends(ZoneQueueRunner, _super);
function ZoneQueueRunner(attrs) {
function ZoneQueueRunner(attrs: {onComplete: Function}) {
attrs.onComplete = ((fn) => () => {
// All functions are done, clear the test zone.
testProxyZone = null;
Expand Down
Loading

0 comments on commit ca7ef1f

Please sign in to comment.