chore(lint): add @typescript-eslint/no-unnecessary-type-assertion rule (#898)

This commit is contained in:
Joel Einbinder 2020-02-07 13:38:50 -08:00 committed by GitHub
parent 487d394f3b
commit 73148fda79
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 49 additions and 46 deletions

View File

@ -106,6 +106,9 @@ module.exports = {
"indent": [2, 2, { "SwitchCase": 1, "CallExpression": {"arguments": 2}, "MemberExpression": 2 }],
"key-spacing": [2, {
"beforeColon": false
}]
}],
// type-aware rules
"@typescript-eslint/no-unnecessary-type-assertion": 2,
}
};

View File

@ -287,7 +287,7 @@ export class CRBrowser extends platform.EventEmitter implements Browser {
this._tracingClient.once('Tracing.tracingComplete', event => {
readProtocolStream(this._tracingClient!, event.stream!, this._tracingPath).then(fulfill);
});
await this._tracingClient!.send('Tracing.end');
await this._tracingClient.send('Tracing.end');
this._tracingRecording = false;
return contentPromise;
}

View File

@ -38,7 +38,7 @@ export class CRExecutionContext implements js.ExecutionContextDelegate {
if (helper.isString(pageFunction)) {
const contextId = this._contextId;
const expression: string = pageFunction as string;
const expression: string = pageFunction;
const expressionWithSourceUrl = SOURCE_URL_REGEX.test(expression) ? expression : expression + '\n' + suffix;
const {exceptionDetails, result: remoteObject} = await this._client.send('Runtime.evaluate', {
expression: expressionWithSourceUrl,

View File

@ -282,12 +282,12 @@ export class CRPage implements PageDelegate {
_onDialog(event: Protocol.Page.javascriptDialogOpeningPayload) {
this._page.emit(Events.Page.Dialog, new dialog.Dialog(
event.type as dialog.DialogType,
event.message,
async (accept: boolean, promptText?: string) => {
await this._client.send('Page.handleJavaScriptDialog', { accept, promptText });
},
event.defaultPrompt));
event.type,
event.message,
async (accept: boolean, promptText?: string) => {
await this._client.send('Page.handleJavaScriptDialog', { accept, promptText });
},
event.defaultPrompt));
}
_handleException(exceptionDetails: Protocol.Runtime.ExceptionDetails) {

View File

@ -48,9 +48,9 @@ function convertPrintParameterToInches(parameter: (string | number | undefined))
let pixels: number;
if (helper.isNumber(parameter)) {
// Treat numbers as pixel values to be aligned with phantom's paperSize.
pixels = parameter as number;
pixels = parameter;
} else if (helper.isString(parameter)) {
const text: string = parameter as string;
const text: string = parameter;
let unit = text.substring(text.length - 2).toLowerCase();
let valueText = '';
if (unitToPixels.hasOwnProperty(unit)) {

View File

@ -119,7 +119,7 @@ export class FFPage implements PageDelegate {
if (!context)
return;
this._contextIdToContext.delete(executionContextId);
context.frame._contextDestroyed(context as dom.FrameExecutionContext);
context.frame._contextDestroyed(context);
}
private _removeContextsForFrame(frame: frames.Frame) {
@ -180,12 +180,12 @@ export class FFPage implements PageDelegate {
_onDialogOpened(params: Protocol.Page.dialogOpenedPayload) {
this._page.emit(Events.Page.Dialog, new dialog.Dialog(
params.type as dialog.DialogType,
params.message,
async (accept: boolean, promptText?: string) => {
await this._session.send('Page.handleDialog', { dialogId: params.dialogId, accept, promptText }).catch(debugError);
},
params.defaultValue));
params.type,
params.message,
async (accept: boolean, promptText?: string) => {
await this._session.send('Page.handleDialog', { dialogId: params.dialogId, accept, promptText }).catch(debugError);
},
params.defaultValue));
}
_onBindingCalled(event: Protocol.Page.bindingCalledPayload) {

View File

@ -767,9 +767,9 @@ export class Frame {
async waitFor(selectorOrFunctionOrTimeout: (string | number | Function), options: types.WaitForFunctionOptions & { visibility?: types.Visibility } = {}, ...args: any[]): Promise<js.JSHandle | null> {
if (helper.isString(selectorOrFunctionOrTimeout))
return this.waitForSelector(selectorOrFunctionOrTimeout as string, options) as any;
return this.waitForSelector(selectorOrFunctionOrTimeout, options) as any;
if (helper.isNumber(selectorOrFunctionOrTimeout))
return new Promise(fulfill => setTimeout(fulfill, selectorOrFunctionOrTimeout as number));
return new Promise(fulfill => setTimeout(fulfill, selectorOrFunctionOrTimeout));
if (typeof selectorOrFunctionOrTimeout === 'function')
return this.waitForFunction(selectorOrFunctionOrTimeout, options, ...args);
return Promise.reject(new Error('Unsupported target type: ' + (typeof selectorOrFunctionOrTimeout)));

View File

@ -30,7 +30,7 @@ class Helper {
static evaluationString(fun: Function | string, ...args: any[]): string {
if (Helper.isString(fun)) {
assert(args.length === 0, 'Cannot evaluate a string with arguments');
return fun as string;
return fun;
}
return `(${fun})(${args.map(serializeArgument).join(',')})`;

View File

@ -64,7 +64,7 @@ export const CSSEngine: SelectorEngine = {
// Ordinal is the weakest signal.
if (parent) {
const siblings = Array.from(parent.children);
const sameTagSiblings = siblings.filter(sibling => (sibling as Element).nodeName.toLowerCase() === nodeName);
const sameTagSiblings = siblings.filter(sibling => (sibling).nodeName.toLowerCase() === nodeName);
const token = sameTagSiblings.length === 1 ? nodeName : `${nodeName}:nth-child(${1 + siblings.indexOf(element)})`;
const selector = uniqueCSSSelector(token);
if (selector)

View File

@ -26,7 +26,7 @@ export const XPathEngine: SelectorEngine = {
const maybeDocument = root instanceof Document ? root : root.ownerDocument;
if (!maybeDocument)
return;
const document = maybeDocument!;
const document = maybeDocument;
const xpathCache = new Map<string, Element[]>();
if (type === 'notext')
@ -135,7 +135,7 @@ export const XPathEngine: SelectorEngine = {
let tagWithOrdinal = tag;
if (parent) {
const siblings = Array.from(parent.children);
const sameTagSiblings = siblings.filter(sibling => (sibling as Element).nodeName.toLowerCase() === nodeName);
const sameTagSiblings = siblings.filter(sibling => (sibling).nodeName.toLowerCase() === nodeName);
if (sameTagSiblings.length > 1)
tagWithOrdinal += `[${1 + siblings.indexOf(element)}]`;
}

View File

@ -780,9 +780,9 @@ const ZSSelectorEngine: SelectorEngine = {
while (e && e.namespaceURI && e.namespaceURI.endsWith('svg') && e.nodeName.toLowerCase() !== 'svg')
e = e.parentElement!;
try {
document.documentElement!.style!.outline = '1px solid red';
document.documentElement.style.outline = '1px solid red';
const selector = new Engine().create(document.documentElement, e, 'default');
document.documentElement!.style!.outline = '1px solid green';
document.documentElement.style.outline = '1px solid green';
const e2 = new Engine().query(document.documentElement, selector, false)[0];
return e !== e2;
} catch (e) {

View File

@ -100,7 +100,7 @@ export class Screenshotter {
let maybeBoundingBox = await this._page._delegate.getBoundingBoxForScreenshot(handle);
assert(maybeBoundingBox, 'Node is either not visible or not an HTMLElement');
let boundingBox = maybeBoundingBox!;
let boundingBox = maybeBoundingBox;
assert(boundingBox.width !== 0, 'Node has 0 width.');
assert(boundingBox.height !== 0, 'Node has 0 height.');
boundingBox = enclosingIntRect(boundingBox);
@ -118,7 +118,7 @@ export class Screenshotter {
});
if (!maybeViewportSize)
throw new Error(kScreenshotDuringNavigationError);
viewportSize = maybeViewportSize!;
viewportSize = maybeViewportSize;
} else {
viewportSize = originalViewportSize;
}
@ -133,7 +133,7 @@ export class Screenshotter {
await handle.scrollIntoViewIfNeeded();
maybeBoundingBox = await this._page._delegate.getBoundingBoxForScreenshot(handle);
assert(maybeBoundingBox, 'Node is either not visible or not an HTMLElement');
boundingBox = enclosingIntRect(maybeBoundingBox!);
boundingBox = enclosingIntRect(maybeBoundingBox);
}
if (!overridenViewportSize)

View File

@ -337,7 +337,7 @@ function wrapTransportWithWebSocket(transport: ConnectionTransport, port: number
if (method === 'Browser.provisionalLoadFailed') {
const socket = pageProxyIds.get(params.pageProxyId);
if (socket && socket.readyState !== ws.CLOSING)
socket!.send(message);
socket.send(message);
return;
}
};

View File

@ -197,8 +197,8 @@ export class WKBrowser extends platform.EventEmitter implements Browser {
close: async (): Promise<void> => {
assert(browserContextId, 'Non-incognito profiles cannot be closed!');
await this._browserSession.send('Browser.deleteContext', { browserContextId: browserContextId! });
this._contexts.delete(browserContextId!);
await this._browserSession.send('Browser.deleteContext', { browserContextId: browserContextId });
this._contexts.delete(browserContextId);
},
cookies: async (): Promise<network.NetworkCookie[]> => {

View File

@ -72,7 +72,7 @@ export class WKExecutionContext implements js.ExecutionContextDelegate {
private async _evaluateRemoteObject(pageFunction: Function | string, args: any[]): Promise<any> {
if (helper.isString(pageFunction)) {
const contextId = this._contextId;
const expression: string = pageFunction as string;
const expression: string = pageFunction;
const expressionWithSourceUrl = SOURCE_URL_REGEX.test(expression) ? expression : expression + '\n' + suffix;
return await this._session.send('Runtime.evaluate', {
expression: expressionWithSourceUrl,

View File

@ -156,9 +156,9 @@ export class WKPage implements PageDelegate {
onProvisionalLoadCommitted(session: WKSession) {
assert(this._provisionalPage);
assert(this._provisionalPage!._session === session);
this._provisionalPage!.commit();
this._provisionalPage!.dispose();
assert(this._provisionalPage._session === session);
this._provisionalPage.commit();
this._provisionalPage.dispose();
this._provisionalPage = null;
this._setSession(session);
}
@ -260,7 +260,7 @@ export class WKPage implements PageDelegate {
private _onFrameNavigated(framePayload: Protocol.Page.Frame, initial: boolean) {
const frame = this._page._frameManager.frame(framePayload.id);
assert(frame);
this._removeContextsForFrame(frame!, true);
this._removeContextsForFrame(frame, true);
if (!framePayload.parentId)
this._workers.clear();
this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url, framePayload.name || '', framePayload.loaderId, initial);
@ -306,7 +306,7 @@ export class WKPage implements PageDelegate {
if (this._pageProxySession.isDisposed())
throw new Error('Target closed');
const pageProxyId = this._pageProxySession.sessionId;
const result = await this._pageProxySession.connection!.browserSession.send('Browser.navigate', { url, pageProxyId, frameId: frame._id, referrer });
const result = await this._pageProxySession.connection.browserSession.send('Browser.navigate', { url, pageProxyId, frameId: frame._id, referrer });
return { newDocumentId: result.loaderId, isSameDocument: !result.loaderId };
}

View File

@ -119,9 +119,9 @@ export class WKPageProxy {
return null;
return await pageProxy.page();
});
await this._wkPage.initialize(session!);
await this._wkPage.initialize(session);
if (this._pagePausedOnStart) {
this._resumeTarget(session!.sessionId);
this._resumeTarget(session.sessionId);
this._pagePausedOnStart = false;
}
return this._wkPage._page;
@ -169,17 +169,17 @@ export class WKPageProxy {
const { targetId, crashed } = event;
const session = this._sessions.get(targetId);
assert(session, 'Unknown target destroyed: ' + targetId);
session!.dispose();
session.dispose();
this._sessions.delete(targetId);
if (this._wkPage)
this._wkPage.onSessionDestroyed(session!, crashed);
this._wkPage.onSessionDestroyed(session, crashed);
}
private _onDispatchMessageFromTarget(event: Protocol.Target.dispatchMessageFromTargetPayload) {
const { targetId, message } = event;
const session = this._sessions.get(targetId);
assert(session, 'Unknown target: ' + targetId);
session!.dispatchMessage(JSON.parse(message));
session.dispatchMessage(JSON.parse(message));
}
private _onDidCommitProvisionalTarget(event: Protocol.Target.didCommitProvisionalTargetPayload) {
@ -189,9 +189,9 @@ export class WKPageProxy {
const oldSession = this._sessions.get(oldTargetId);
assert(oldSession, 'Unknown old target: ' + oldTargetId);
// TODO: make some calls like screenshot catch swapped out error and retry.
oldSession!.errorText = 'Target was swapped out.';
oldSession.errorText = 'Target was swapped out.';
(newSession as any)[isPovisionalSymbol] = undefined;
if (this._wkPage)
this._wkPage.onProvisionalLoadCommitted(newSession!);
this._wkPage.onProvisionalLoadCommitted(newSession);
}
}

View File

@ -57,7 +57,7 @@ export class WKProvisionalPage {
commit() {
assert(this._mainFrameId);
this._wkPage._onFrameAttached(this._mainFrameId!, null);
this._wkPage._onFrameAttached(this._mainFrameId, null);
}
private _handleFrameTree(frameTree: Protocol.Page.FrameResourceTree) {