Skip to content

Commit

Permalink
style(aio): enforce strict TypeScript checks
Browse files Browse the repository at this point in the history
Closes #20646
  • Loading branch information
petebacondarwin committed Jan 11, 2018
1 parent c6eb9ee commit 537e4d0
Show file tree
Hide file tree
Showing 57 changed files with 198 additions and 194 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
"@angular/core": "^5.0.0",
"@angular/forms": "^5.0.0",
"@angular/http": "^5.0.0",
"@angular/service-worker": "^5.0.0",
"@angular/platform-browser": "^5.0.0",
"@angular/platform-browser-dynamic": "^5.0.0",
"@angular/router": "^5.0.0",
Expand Down
2 changes: 1 addition & 1 deletion aio/e2e/api.po.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export class ApiPage extends SitePage {
// and we want to be able to pull out the code elements from only the first level
// if `onlyDirect` is set to `true`.
const selector = `.descendants.${docType} ${onlyDirect ? '>' : ''} li > :not(ul) code`;
return element.all(by.css(selector)).map<string>(item => item.getText());
return element.all(by.css(selector)).map<string>(item => item && item.getText());
}

getOverview(docType) {
Expand Down
2 changes: 1 addition & 1 deletion aio/e2e/app.po.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,6 @@ export class SitePage {
getSearchResults() {
const results = element.all(by.css('.search-results li'));
browser.wait(ExpectedConditions.presenceOf(results.first()), 8000);
return results.map(link => link.getText());
return results.map(link => link && link.getText());
}
}
24 changes: 12 additions & 12 deletions aio/src/app/app.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ describe('AppComponent', () => {
it('should not navigate when change to a version without a url', () => {
setupSelectorForTesting();
const versionWithoutUrlIndex = component.docVersions.length;
const versionWithoutUrl = component.docVersions[versionWithoutUrlIndex] = { title: 'foo', url: null };
const versionWithoutUrl = component.docVersions[versionWithoutUrlIndex] = { title: 'foo' };
selectElement.triggerEventHandler('change', { option: versionWithoutUrl, index: versionWithoutUrlIndex });
expect(locationService.go).not.toHaveBeenCalled();
});
Expand Down Expand Up @@ -520,9 +520,9 @@ describe('AppComponent', () => {

describe('aio-toc', () => {
let tocDebugElement: DebugElement;
let tocContainer: DebugElement;
let tocContainer: DebugElement|null;

const setHasFloatingToc = hasFloatingToc => {
const setHasFloatingToc = (hasFloatingToc: boolean) => {
component.hasFloatingToc = hasFloatingToc;
fixture.detectChanges();

Expand Down Expand Up @@ -551,12 +551,12 @@ describe('AppComponent', () => {
});

it('should update the TOC container\'s `maxHeight` based on `tocMaxHeight`', () => {
expect(tocContainer.styles['max-height']).toBeNull();
expect(tocContainer!.styles['max-height']).toBeNull();

component.tocMaxHeight = '100';
fixture.detectChanges();

expect(tocContainer.styles['max-height']).toBe('100px');
expect(tocContainer!.styles['max-height']).toBe('100px');
});

it('should restrain scrolling inside the ToC container', () => {
Expand All @@ -565,7 +565,7 @@ describe('AppComponent', () => {

expect(restrainScrolling).not.toHaveBeenCalled();

tocContainer.triggerEventHandler('mousewheel', evt);
tocContainer!.triggerEventHandler('mousewheel', evt);
expect(restrainScrolling).toHaveBeenCalledWith(evt);
});
});
Expand All @@ -591,7 +591,7 @@ describe('AppComponent', () => {
initializeTest();
fixture.detectChanges();
const banner: HTMLElement = fixture.debugElement.query(By.css('aio-mode-banner')).nativeElement;
expect(banner.textContent.trim()).toEqual('');
expect(banner.textContent!.trim()).toEqual('');
});
});

Expand Down Expand Up @@ -985,9 +985,9 @@ describe('AppComponent', () => {
checkHostClass('mode', 'archive');
});

function checkHostClass(type, value) {
function checkHostClass(type: string, value: string) {
const host = fixture.debugElement;
const classes = host.properties['className'];
const classes: string = host.properties['className'];
const classArray = classes.split(' ').filter(c => c.indexOf(`${type}-`) === 0);
expect(classArray.length).toBeLessThanOrEqual(1, `"${classes}" should have only one class matching ${type}-*`);
expect(classArray).toEqual([`${type}-${value}`], `"${classes}" should contain ${type}-${value}`);
Expand Down Expand Up @@ -1212,10 +1212,10 @@ class TestHttpClient {
if (/navigation\.json/.test(url)) {
data = this.navJson;
} else {
const match = /generated\/docs\/(.+)\.json/.exec(url);
const id = match[1];
const match = /generated\/docs\/(.+)\.json/.exec(url)!;
const id = match[1]!;
// Make up a title for test purposes
const title = id.split('/').pop().replace(/^([a-z])/, (_, letter) => letter.toUpperCase());
const title = id.split('/').pop()!.replace(/^([a-z])/, (_, letter) => letter.toUpperCase());
const h1 = (id === 'no-title') ? '' : `<h1>${title}</h1>`;
const contents = `${h1}<h2 id="#somewhere">Some heading</h2>`;
data = { id, contents };
Expand Down
16 changes: 8 additions & 8 deletions aio/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,19 +147,19 @@ export class AppComponent implements OnInit {
this.navigationService.navigationViews.map(views => views['docVersions']))
.subscribe(([versionInfo, versions]) => {
// TODO(pbd): consider whether we can lookup the stable and next versions from the internet
const computedVersions = [
const computedVersions: NavigationNode[] = [
{ title: 'next', url: 'https://next.angular.io' },
{ title: 'stable', url: 'https://angular.io' },
];
if (this.deployment.mode === 'archive') {
computedVersions.push({ title: `v${versionInfo.major}`, url: null });
computedVersions.push({ title: `v${versionInfo.major}` });
}
this.docVersions = [...computedVersions, ...versions];

// Find the current version - eithers title matches the current deployment mode
// or its title matches the major version of the current version info
this.currentDocVersion = this.docVersions.find(version =>
version.title === this.deployment.mode || version.title === `v${versionInfo.major}`);
version.title === this.deployment.mode || version.title === `v${versionInfo.major}`)!;
this.currentDocVersion.title += ` (v${versionInfo.raw})`;
});

Expand Down Expand Up @@ -227,7 +227,7 @@ export class AppComponent implements OnInit {
}

@HostListener('window:resize', ['$event.target.innerWidth'])
onResize(width) {
onResize(width: number) {
this.isSideBySide = width > this.sideBySideWidth;
this.showFloatingToc.next(width > this.showFloatingTocWidth);
}
Expand All @@ -247,7 +247,7 @@ export class AppComponent implements OnInit {
}

// Deal with anchor clicks; climb DOM tree until anchor found (or null)
let target = eventTarget;
let target: HTMLElement|null = eventTarget;
while (target && !(target instanceof HTMLAnchorElement)) {
target = target.parentElement;
}
Expand Down Expand Up @@ -311,8 +311,8 @@ export class AppComponent implements OnInit {
// Must wait until now for mat-toolbar to be measurable.
const el = this.hostElement.nativeElement as Element;
this.tocMaxHeightOffset =
el.querySelector('footer').clientHeight +
el.querySelector('.app-toolbar').clientHeight +
el.querySelector('footer')!.clientHeight +
el.querySelector('.app-toolbar')!.clientHeight +
24; // fudge margin
}

Expand Down Expand Up @@ -351,7 +351,7 @@ export class AppComponent implements OnInit {
}
}

doSearch(query) {
doSearch(query: string) {
this.searchResults = this.searchService.search(query);
this.showSearchResults = !!query;
}
Expand Down
4 changes: 2 additions & 2 deletions aio/src/app/app.module.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ describe('AppModule', () => {
});

it('should provide a list of eagerly-loaded embedded components', () => {
const eagerSelector = Object.keys(componentsMap).find(selector => Array.isArray(componentsMap[selector]));
const eagerSelector = Object.keys(componentsMap).find(selector => Array.isArray(componentsMap[selector]))!;
const selectorCount = eagerSelector.split(',').length;

expect(eagerSelector).not.toBeNull();
Expand All @@ -34,7 +34,7 @@ describe('AppModule', () => {
});

it('should provide a list of lazy-loaded embedded components', () => {
const lazySelector = Object.keys(componentsMap).find(selector => selector.includes('code-example'));
const lazySelector = Object.keys(componentsMap).find(selector => selector.includes('code-example'))!;
const selectorCount = lazySelector.split(',').length;

expect(lazySelector).not.toBeNull();
Expand Down
2 changes: 1 addition & 1 deletion aio/src/app/documents/document-contents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ export interface DocumentContents {
/** The unique identifier for this document */
id: string;
/** The HTML to display in the doc viewer */
contents: string;
contents: string|null;
}
16 changes: 8 additions & 8 deletions aio/src/app/documents/document.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ describe('DocumentService', () => {
});

it('should emit a document each time the location changes', () => {
let latestDocument: DocumentContents;
let latestDocument: DocumentContents|undefined;
const doc0 = { contents: 'doc 0', id: 'initial/doc' };
const doc1 = { contents: 'doc 1', id: 'new/doc' };
const { docService, locationService } = getServices('initial/doc');
Expand All @@ -67,7 +67,7 @@ describe('DocumentService', () => {
});

it('should emit the not-found document if the document is not found on the server', () => {
let currentDocument: DocumentContents;
let currentDocument: DocumentContents|undefined;
const notFoundDoc = { id: FILE_NOT_FOUND_ID, contents: '<h1>Page Not Found</h1>' };
const { docService } = getServices('missing/doc');
docService.currentDocument.subscribe(doc => currentDocument = doc);
Expand All @@ -82,7 +82,7 @@ describe('DocumentService', () => {
});

it('should emit a hard-coded not-found document if the not-found document is not found on the server', () => {
let currentDocument: DocumentContents;
let currentDocument: DocumentContents|undefined;
const hardCodedNotFoundDoc = { contents: 'Document not found', id: FILE_NOT_FOUND_ID };
const nextDoc = { contents: 'Next Doc', id: 'new/doc' };
const { docService, locationService } = getServices(FILE_NOT_FOUND_ID);
Expand All @@ -99,15 +99,15 @@ describe('DocumentService', () => {
});

it('should use a hard-coded error doc if the request fails (but not cache it)', () => {
let latestDocument: DocumentContents;
let latestDocument: DocumentContents|undefined;
const doc1 = { contents: 'doc 1' };
const doc2 = { contents: 'doc 2' };
const { docService, locationService } = getServices('initial/doc');

docService.currentDocument.subscribe(doc => latestDocument = doc);

httpMock.expectOne({}).flush(null, {status: 500, statusText: 'Server Error'});
expect(latestDocument.id).toEqual(FETCHING_ERROR_ID);
expect(latestDocument!.id).toEqual(FETCHING_ERROR_ID);

locationService.go('new/doc');
httpMock.expectOne({}).flush(doc1);
Expand All @@ -119,22 +119,22 @@ describe('DocumentService', () => {
});

it('should not crash the app if the response is invalid JSON', () => {
let latestDocument: DocumentContents;
let latestDocument: DocumentContents|undefined;
const doc1 = { contents: 'doc 1' };
const { docService, locationService } = getServices('initial/doc');

docService.currentDocument.subscribe(doc => latestDocument = doc);

httpMock.expectOne({}).flush('this is invalid JSON');
expect(latestDocument.id).toEqual(FETCHING_ERROR_ID);
expect(latestDocument!.id).toEqual(FETCHING_ERROR_ID);

locationService.go('new/doc');
httpMock.expectOne({}).flush(doc1);
expect(latestDocument).toEqual(jasmine.objectContaining(doc1));
});

it('should not make a request to the server if the doc is in the cache already', () => {
let latestDocument: DocumentContents;
let latestDocument: DocumentContents|undefined;
let subscription: Subscription;

const doc0 = { contents: 'doc 0' };
Expand Down
2 changes: 1 addition & 1 deletion aio/src/app/documents/document.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class DocumentService {
if ( !this.cache.has(id)) {
this.cache.set(id, this.fetchDocument(id));
}
return this.cache.get(id);
return this.cache.get(id)!;
}

private fetchDocument(id: string): Observable<DocumentContents> {
Expand Down
4 changes: 2 additions & 2 deletions aio/src/app/embed-components/embed-components.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,9 @@ describe('EmbedComponentsService', () => {
const componentRefs = service.createComponents(host);
componentRefs[0].changeDetectorRef.detectChanges();

const barEl = host.querySelector('aio-eager-bar');
const barEl = host.querySelector('aio-eager-bar')!;

expect(barEl['aioEagerBarContent']).toBe(projectedContent);
expect((barEl as any)['aioEagerBarContent']).toBe(projectedContent);
expect(barEl.innerHTML).toContain(projectedContent);
});

Expand Down
4 changes: 2 additions & 2 deletions aio/src/app/embed-components/embed-components.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export class EmbedComponentsService {
// Hack: Preserve the current element content, because the factory will empty it out.
// Security: The source of this `innerHTML` should always be authored by the documentation
// team and is considered to be safe.
host[contentPropertyName] = host.innerHTML;
(host as any)[contentPropertyName] = host.innerHTML;
componentRefs.push(factory.create(this.injector, [], host));
}
});
Expand Down Expand Up @@ -141,7 +141,7 @@ export class EmbedComponentsService {
this.componentFactoriesReady.set(compsOrPath, readyPromise);
}

return this.componentFactoriesReady.get(compsOrPath);
return this.componentFactoriesReady.get(compsOrPath)!;
}

/**
Expand Down
6 changes: 3 additions & 3 deletions aio/src/app/embedded/api/api-list.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ describe('ApiListComponent', () => {
*/
function expectFilteredResult(label: string, itemTest: (item: ApiItem) => boolean) {
component.filteredSections.subscribe(filtered => {
let badItem: ApiItem;
let badItem: ApiItem|undefined;
expect(filtered.length).toBeGreaterThan(0, 'expected something');
expect(filtered.every(section => section.items.every(
item => {
Expand All @@ -53,7 +53,7 @@ describe('ApiListComponent', () => {
});

it('should return all complete sections when no criteria', () => {
let filtered: ApiSection[];
let filtered: ApiSection[]|undefined;
component.filteredSections.subscribe(f => filtered = f);
expect(filtered).toEqual(sections);
});
Expand All @@ -68,7 +68,7 @@ describe('ApiListComponent', () => {
component.filteredSections.subscribe(filtered => {
expect(filtered.length).toBe(1, 'only one section');
expect(filtered[0].name).toBe('core');
expect(filtered[0].items.every(item => item.show)).toBe(true, 'all core items shown');
expect(filtered[0].items.every(item => !!item.show)).toBe(true, 'all core items shown');
});
});

Expand Down
4 changes: 2 additions & 2 deletions aio/src/app/embedded/api/api.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ describe('ApiService', () => {
let completed = false;

service.sections.subscribe(
null,
null,
undefined,
undefined,
() => completed = true
);

Expand Down
2 changes: 1 addition & 1 deletion aio/src/app/embedded/code/code-example.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export class CodeExampleComponent implements OnInit {
const element: HTMLElement = this.elementRef.nativeElement;

this.language = element.getAttribute('language') || '';
this.linenums = element.getAttribute('linenums');
this.linenums = element.getAttribute('linenums') || '';
this.path = element.getAttribute('path') || '';
this.region = element.getAttribute('region') || '';
this.title = element.getAttribute('title') || '';
Expand Down
6 changes: 3 additions & 3 deletions aio/src/app/embedded/code/code-tabs.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
import { Component, ElementRef, OnInit } from '@angular/core';

export interface TabInfo {
class: string;
class: string|null;
code: string;
language: string;
language: string|null;
linenums: any;
path: string;
region: string;
title: string;
title: string|null;
}

/**
Expand Down
4 changes: 2 additions & 2 deletions aio/src/app/embedded/code/code.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ describe('CodeComponent', () => {
// we take strict measures to wipe it out in the `afterAll`
// and make sure THAT runs after the tests by making component creation async
afterAll(() => {
delete window['prettyPrint'];
delete window['prettyPrintOne'];
delete (window as any)['prettyPrint'];
delete (window as any)['prettyPrintOne'];
});

beforeEach(() => {
Expand Down
2 changes: 1 addition & 1 deletion aio/src/app/embedded/code/code.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ export class CodeComponent implements OnChanges {
}
}

function leftAlign(text) {
function leftAlign(text: string) {
let indent = Number.MAX_VALUE;
const lines = text.split('\n');
lines.forEach(line => {
Expand Down

0 comments on commit 537e4d0

Please sign in to comment.