Skip to content

Commit 09d9f5f

Browse files
mheveryhansl
authored andcommitted
fix(compiler): Update types for TypeScript nullability support
1 parent d8b73e4 commit 09d9f5f

File tree

118 files changed

+2086
-1859
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

118 files changed

+2086
-1859
lines changed

packages/compiler-cli/src/compiler_host.ts

+6-5
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export class CompilerHost implements AotCompilerHost {
3333
private resolverCache = new Map<string, ModuleMetadata[]>();
3434
private bundleIndexCache = new Map<string, boolean>();
3535
private bundleIndexNames = new Set<string>();
36-
private moduleFileNames = new Map<string, string>();
36+
private moduleFileNames = new Map<string, string|null>();
3737
protected resolveModuleNameHost: CompilerHostContext;
3838

3939
constructor(
@@ -71,7 +71,7 @@ export class CompilerHost implements AotCompilerHost {
7171

7272
moduleNameToFileName(m: string, containingFile: string): string|null {
7373
const key = m + ':' + (containingFile || '');
74-
let result = this.moduleFileNames.get(key);
74+
let result: string|null = this.moduleFileNames.get(key) || null;
7575
if (!result) {
7676
if (!containingFile || !containingFile.length) {
7777
if (m.indexOf('.') === 0) {
@@ -183,7 +183,7 @@ export class CompilerHost implements AotCompilerHost {
183183
return sf;
184184
}
185185

186-
getMetadataFor(filePath: string): ModuleMetadata[] {
186+
getMetadataFor(filePath: string): ModuleMetadata[]|undefined {
187187
if (!this.context.fileExists(filePath)) {
188188
// If the file doesn't exists then we cannot return metadata for the file.
189189
// This will occur if the user refernced a declared module for which no file
@@ -263,6 +263,7 @@ export class CompilerHost implements AotCompilerHost {
263263
if (this.context.fileExists(filePath)) {
264264
return this.context.readFile(filePath);
265265
}
266+
return null;
266267
}
267268

268269
getOutputFileName(sourceFilePath: string): string {
@@ -287,7 +288,7 @@ export class CompilerHost implements AotCompilerHost {
287288

288289
calculateEmitPath(filePath: string): string {
289290
// Write codegen in a directory structure matching the sources.
290-
let root = this.options.basePath;
291+
let root = this.options.basePath !;
291292
for (const eachRootDir of this.options.rootDirs || []) {
292293
if (this.options.trace) {
293294
console.error(`Check if ${filePath} is under rootDirs element ${eachRootDir}`);
@@ -373,7 +374,7 @@ export class ModuleResolutionHostAdapter extends CompilerHostContextAdapter impl
373374
constructor(private host: ts.ModuleResolutionHost) {
374375
super();
375376
if (host.directoryExists) {
376-
this.directoryExists = (directoryName: string) => host.directoryExists(directoryName);
377+
this.directoryExists = (directoryName: string) => host.directoryExists !(directoryName);
377378
}
378379
}
379380

packages/compiler-cli/src/extract_i18n.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ function extract(
2323
ngOptions: tsc.AngularCompilerOptions, cliOptions: tsc.I18nExtractionCliOptions,
2424
program: ts.Program, host: ts.CompilerHost): Promise<void> {
2525
return Extractor.create(ngOptions, program, host, cliOptions.locale)
26-
.extract(cliOptions.i18nFormat, cliOptions.outFile);
26+
.extract(cliOptions.i18nFormat !, cliOptions.outFile);
2727
}
2828

2929
// Entry point

packages/compiler-cli/src/ngtools_api.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,9 @@ export class NgTools_InternalApi_NG_2 {
9292
const hostContext: CompilerHostContext =
9393
new CustomLoaderModuleResolutionHostAdapter(options.readResource, options.host);
9494
const cliOptions: NgcCliOptions = {
95-
i18nFormat: options.i18nFormat,
96-
i18nFile: options.i18nFile,
97-
locale: options.locale,
95+
i18nFormat: options.i18nFormat !,
96+
i18nFile: options.i18nFile !,
97+
locale: options.locale !,
9898
basePath: options.basePath
9999
};
100100

@@ -148,6 +148,6 @@ export class NgTools_InternalApi_NG_2 {
148148
const extractor = Extractor.create(
149149
options.angularCompilerOptions, options.program, options.host, locale, hostContext);
150150

151-
return extractor.extract(options.i18nFormat, options.outFile || null);
151+
return extractor.extract(options.i18nFormat !, options.outFile || null);
152152
}
153153
}

packages/compiler-cli/src/ngtools_impl.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ export type LazyRouteMap = {
3333
// A route definition. Normally the short form 'path/to/module#ModuleClassName' is used by
3434
// the user, and this is a helper class to extract information from it.
3535
export class RouteDef {
36-
private constructor(public readonly path: string, public readonly className: string = null) {}
36+
private constructor(public readonly path: string, public readonly className: string|null = null) {
37+
}
3738

3839
toString() {
3940
return (this.className === null || this.className == 'default') ?
@@ -58,7 +59,7 @@ export function listLazyRoutesOfModule(
5859
const entryRouteDef = RouteDef.fromString(entryModule);
5960
const containingFile = _resolveModule(entryRouteDef.path, entryRouteDef.path, host);
6061
const modulePath = `./${containingFile.replace(/^(.*)\//, '')}`;
61-
const className = entryRouteDef.className;
62+
const className = entryRouteDef.className !;
6263

6364
// List loadChildren of this single module.
6465
const appStaticSymbol = reflector.findDeclaration(modulePath, className, containingFile);

packages/compiler-cli/src/path_mapped_compiler_host.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ export class PathMappedCompilerHost extends CompilerHost {
4040
return fileName;
4141
}
4242

43-
moduleNameToFileName(m: string, containingFile: string) {
43+
moduleNameToFileName(m: string, containingFile: string): string|null {
4444
if (!containingFile || !containingFile.length) {
4545
if (m.indexOf('.') === 0) {
4646
throw new Error('Resolution of relative paths requires a containing file.');
@@ -59,6 +59,7 @@ export class PathMappedCompilerHost extends CompilerHost {
5959
return this.getCanonicalFileName(resolved.resolvedFileName);
6060
}
6161
}
62+
return null;
6263
}
6364

6465
/**
@@ -90,7 +91,7 @@ export class PathMappedCompilerHost extends CompilerHost {
9091

9192
const importModuleName = importedFile.replace(EXT, '');
9293
const parts = importModuleName.split(path.sep).filter(p => !!p);
93-
let foundRelativeImport: string;
94+
let foundRelativeImport: string = undefined !;
9495
for (let index = parts.length - 1; index >= 0; index--) {
9596
let candidate = parts.slice(index, parts.length).join(path.sep);
9697
if (resolvable(candidate)) {
@@ -135,5 +136,6 @@ export class PathMappedCompilerHost extends CompilerHost {
135136
return metadata ? [metadata] : [];
136137
}
137138
}
139+
return null !;
138140
}
139141
}

packages/compiler-cli/tsconfig-build.json

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
"declaration": true,
55
"experimentalDecorators": true,
66
"noImplicitAny": true,
7+
"strictNullChecks": true,
78
"module": "commonjs",
89
"outDir": "../../dist/packages/compiler-cli",
910
"paths": {

packages/compiler/src/aot/compiler.ts

+17-16
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9-
import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompileProviderMetadata, componentFactoryName, createHostComponentMeta, flatten, identifierName, sourceUrl, templateSourceUrl} from '../compile_metadata';
9+
import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompileProviderMetadata, CompileTypeSummary, componentFactoryName, createHostComponentMeta, flatten, identifierName, sourceUrl, templateSourceUrl} from '../compile_metadata';
1010
import {CompilerConfig} from '../config';
1111
import {Identifiers, createIdentifier, createIdentifierToken} from '../identifiers';
1212
import {CompileMetadataResolver} from '../metadata_resolver';
@@ -32,8 +32,8 @@ export class AotCompiler {
3232
private _metadataResolver: CompileMetadataResolver, private _templateParser: TemplateParser,
3333
private _styleCompiler: StyleCompiler, private _viewCompiler: ViewCompiler,
3434
private _ngModuleCompiler: NgModuleCompiler, private _outputEmitter: OutputEmitter,
35-
private _summaryResolver: SummaryResolver<StaticSymbol>, private _localeId: string,
36-
private _translationFormat: string, private _genFilePreamble: string,
35+
private _summaryResolver: SummaryResolver<StaticSymbol>, private _localeId: string|null,
36+
private _translationFormat: string|null, private _genFilePreamble: string|null,
3737
private _symbolResolver: StaticSymbolResolver) {}
3838

3939
clearCache() { this._metadataResolver.clearCache(); }
@@ -113,11 +113,11 @@ export class AotCompiler {
113113
targetExportedVars: string[]): GeneratedFile {
114114
const symbolSummaries = this._symbolResolver.getSymbolsOf(srcFileUrl)
115115
.map(symbol => this._symbolResolver.resolveSymbol(symbol));
116-
const typeSummaries = [
117-
...ngModules.map(ref => this._metadataResolver.getNgModuleSummary(ref)),
118-
...directives.map(ref => this._metadataResolver.getDirectiveSummary(ref)),
119-
...pipes.map(ref => this._metadataResolver.getPipeSummary(ref)),
120-
...injectables.map(ref => this._metadataResolver.getInjectableSummary(ref))
116+
const typeSummaries: CompileTypeSummary[] = [
117+
...ngModules.map(ref => this._metadataResolver.getNgModuleSummary(ref) !),
118+
...directives.map(ref => this._metadataResolver.getDirectiveSummary(ref) !),
119+
...pipes.map(ref => this._metadataResolver.getPipeSummary(ref) !),
120+
...injectables.map(ref => this._metadataResolver.getInjectableSummary(ref) !)
121121
];
122122
const {json, exportAs} = serializeSummaries(
123123
this._summaryResolver, this._symbolResolver, symbolSummaries, typeSummaries);
@@ -130,7 +130,7 @@ export class AotCompiler {
130130
}
131131

132132
private _compileModule(ngModuleType: StaticSymbol, targetStatements: o.Statement[]): string {
133-
const ngModule = this._metadataResolver.getNgModuleMetadata(ngModuleType);
133+
const ngModule = this._metadataResolver.getNgModuleMetadata(ngModuleType) !;
134134
const providers: CompileProviderMetadata[] = [];
135135

136136
if (this._localeId) {
@@ -183,19 +183,19 @@ export class AotCompiler {
183183
o.variable(hostViewFactoryVar), new o.LiteralMapExpr(inputsExprs),
184184
new o.LiteralMapExpr(outputsExprs),
185185
o.literalArr(
186-
compMeta.template.ngContentSelectors.map(selector => o.literal(selector)))
186+
compMeta.template !.ngContentSelectors.map(selector => o.literal(selector)))
187187
]))
188188
.toDeclStmt(
189189
o.importType(
190-
createIdentifier(Identifiers.ComponentFactory), [o.importType(compMeta.type)],
190+
createIdentifier(Identifiers.ComponentFactory), [o.importType(compMeta.type) !],
191191
[o.TypeModifier.Const]),
192192
[o.StmtModifier.Final]));
193193
return compFactoryVar;
194194
}
195195

196196
private _compileComponent(
197197
compMeta: CompileDirectiveMetadata, ngModule: CompileNgModuleMetadata,
198-
directiveIdentifiers: CompileIdentifierMetadata[], componentStyles: CompiledStylesheet,
198+
directiveIdentifiers: CompileIdentifierMetadata[], componentStyles: CompiledStylesheet|null,
199199
fileSuffix: string,
200200
targetStatements: o.Statement[]): {viewClassVar: string, compRenderTypeVar: string} {
201201
const directives =
@@ -204,8 +204,8 @@ export class AotCompiler {
204204
pipe => this._metadataResolver.getPipeSummary(pipe.reference));
205205

206206
const {template: parsedTemplate, pipes: usedPipes} = this._templateParser.parse(
207-
compMeta, compMeta.template.template, directives, pipes, ngModule.schemas,
208-
templateSourceUrl(ngModule.type, compMeta, compMeta.template));
207+
compMeta, compMeta.template !.template !, directives, pipes, ngModule.schemas,
208+
templateSourceUrl(ngModule.type, compMeta, compMeta.template !));
209209
const stylesExpr = componentStyles ? o.variable(componentStyles.stylesVar) : o.literalArr([]);
210210
const viewResult =
211211
this._viewCompiler.compileComponent(compMeta, parsedTemplate, stylesExpr, usedPipes);
@@ -221,8 +221,9 @@ export class AotCompiler {
221221
fileUrl: string, stylesCompileResult: CompiledStylesheet, fileSuffix: string): GeneratedFile {
222222
_resolveStyleStatements(this._symbolResolver, stylesCompileResult, fileSuffix);
223223
return this._codegenSourceModule(
224-
fileUrl, _stylesModuleUrl(
225-
stylesCompileResult.meta.moduleUrl, stylesCompileResult.isShimmed, fileSuffix),
224+
fileUrl,
225+
_stylesModuleUrl(
226+
stylesCompileResult.meta.moduleUrl !, stylesCompileResult.isShimmed, fileSuffix),
226227
stylesCompileResult.statements, [stylesCompileResult.stylesVar]);
227228
}
228229

packages/compiler/src/aot/compiler_factory.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -70,15 +70,16 @@ export function createAotCompiler(compilerHost: AotCompilerHost, options: AotCom
7070
console, symbolCache, staticReflector);
7171
// TODO(vicb): do not pass options.i18nFormat here
7272
const importResolver = {
73-
getImportAs: (symbol: StaticSymbol) => symbolResolver.getImportAs(symbol),
73+
getImportAs: (symbol: StaticSymbol) => symbolResolver.getImportAs(symbol) !,
7474
fileNameToModuleName: (fileName: string, containingFilePath: string) =>
7575
compilerHost.fileNameToModuleName(fileName, containingFilePath),
76-
getTypeArity: (symbol: StaticSymbol) => symbolResolver.getTypeArity(symbol)
76+
getTypeArity: (symbol: StaticSymbol) => symbolResolver.getTypeArity(symbol) !
7777
};
7878
const viewCompiler = new ViewCompiler(config, elementSchemaRegistry);
7979
const compiler = new AotCompiler(
8080
config, compilerHost, resolver, tmplParser, new StyleCompiler(urlResolver), viewCompiler,
8181
new NgModuleCompiler(), new TypeScriptEmitter(importResolver), summaryResolver,
82-
options.locale, options.i18nFormat, options.genFilePreamble, symbolResolver);
82+
options.locale || null, options.i18nFormat || null, options.genFilePreamble || null,
83+
symbolResolver);
8384
return {compiler, reflector: staticReflector};
8485
}

packages/compiler/src/aot/compiler_host.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,7 @@ export interface AotCompilerHost extends StaticSymbolResolverHost, AotSummaryRes
2020
*
2121
* See ImportResolver.
2222
*/
23-
fileNameToModuleName(importedFilePath: string, containingFilePath: string): string
24-
/*|null*/;
23+
fileNameToModuleName(importedFilePath: string, containingFilePath: string): string|null;
2524

2625
/**
2726
* Loads a resource (e.g. html / css)

packages/compiler/src/aot/static_reflection_capabilities.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ export class StaticAndDynamicReflectionCapabilities {
4141
getter(name: string): ɵGetterFn { return this.dynamicDelegate.getter(name); }
4242
setter(name: string): ɵSetterFn { return this.dynamicDelegate.setter(name); }
4343
method(name: string): ɵMethodFn { return this.dynamicDelegate.method(name); }
44-
importUri(type: any): string { return this.staticDelegate.importUri(type); }
44+
importUri(type: any): string { return this.staticDelegate.importUri(type) !; }
4545
resourceUri(type: any): string { return this.staticDelegate.resourceUri(type); }
4646
resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any) {
4747
return this.staticDelegate.resolveIdentifier(name, moduleUrl, members);

packages/compiler/src/aot/static_reflector.ts

+14-14
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ export class StaticReflector implements ɵReflectorReader {
4747
private symbolResolver: StaticSymbolResolver,
4848
knownMetadataClasses: {name: string, filePath: string, ctor: any}[] = [],
4949
knownMetadataFunctions: {name: string, filePath: string, fn: any}[] = [],
50-
private errorRecorder?: (error: any, fileName: string) => void) {
50+
private errorRecorder?: (error: any, fileName?: string) => void) {
5151
this.initializeConversionMap();
5252
knownMetadataClasses.forEach(
5353
(kc) => this._registerDecoratorOrConstructor(
@@ -67,7 +67,7 @@ export class StaticReflector implements ɵReflectorReader {
6767
this.annotationNames.set(Injectable, 'Injectable');
6868
}
6969

70-
importUri(typeOrFunc: StaticSymbol): string {
70+
importUri(typeOrFunc: StaticSymbol): string|null {
7171
const staticSymbol = this.findSymbolDeclaration(typeOrFunc);
7272
return staticSymbol ? staticSymbol.filePath : null;
7373
}
@@ -129,14 +129,14 @@ export class StaticReflector implements ɵReflectorReader {
129129
const summary = this.summaryResolver.resolveSummary(parentType);
130130
if (summary && summary.type) {
131131
const requiredAnnotationTypes =
132-
this.annotationForParentClassWithSummaryKind.get(summary.type.summaryKind);
132+
this.annotationForParentClassWithSummaryKind.get(summary.type.summaryKind !) !;
133133
const typeHasRequiredAnnotation = requiredAnnotationTypes.some(
134-
requiredType => ownAnnotations.some(ann => ann instanceof requiredType));
134+
(requiredType: any) => ownAnnotations.some(ann => ann instanceof requiredType));
135135
if (!typeHasRequiredAnnotation) {
136136
this.reportError(
137137
syntaxError(
138-
`Class ${type.name} in ${type.filePath} extends from a ${CompileSummaryKind[summary.type.summaryKind]} in another compilation unit without duplicating the decorator. ` +
139-
`Please add a ${requiredAnnotationTypes.map(type => this.annotationNames.get(type)).join(' or ')} decorator to the class.`),
138+
`Class ${type.name} in ${type.filePath} extends from a ${CompileSummaryKind[summary.type.summaryKind!]} in another compilation unit without duplicating the decorator. ` +
139+
`Please add a ${requiredAnnotationTypes.map((type: any) => this.annotationNames.get(type)).join(' or ')} decorator to the class.`),
140140
type);
141141
}
142142
}
@@ -155,7 +155,7 @@ export class StaticReflector implements ɵReflectorReader {
155155
if (parentType) {
156156
const parentPropMetadata = this.propMetadata(parentType);
157157
Object.keys(parentPropMetadata).forEach((parentProp) => {
158-
propMetadata[parentProp] = parentPropMetadata[parentProp];
158+
propMetadata ![parentProp] = parentPropMetadata[parentProp];
159159
});
160160
}
161161

@@ -165,10 +165,10 @@ export class StaticReflector implements ɵReflectorReader {
165165
const prop = (<any[]>propData)
166166
.find(a => a['__symbolic'] == 'property' || a['__symbolic'] == 'method');
167167
const decorators: any[] = [];
168-
if (propMetadata[propName]) {
169-
decorators.push(...propMetadata[propName]);
168+
if (propMetadata ![propName]) {
169+
decorators.push(...propMetadata ![propName]);
170170
}
171-
propMetadata[propName] = decorators;
171+
propMetadata ![propName] = decorators;
172172
if (prop && prop['decorators']) {
173173
decorators.push(...this.simplify(type, prop['decorators']));
174174
}
@@ -206,7 +206,7 @@ export class StaticReflector implements ɵReflectorReader {
206206
if (decorators) {
207207
nestedResult.push(...decorators);
208208
}
209-
parameters.push(nestedResult);
209+
parameters !.push(nestedResult);
210210
});
211211
} else if (parentType) {
212212
parameters = this.parameters(parentType);
@@ -232,22 +232,22 @@ export class StaticReflector implements ɵReflectorReader {
232232
if (parentType) {
233233
const parentMethodNames = this._methodNames(parentType);
234234
Object.keys(parentMethodNames).forEach((parentProp) => {
235-
methodNames[parentProp] = parentMethodNames[parentProp];
235+
methodNames ![parentProp] = parentMethodNames[parentProp];
236236
});
237237
}
238238

239239
const members = classMetadata['members'] || {};
240240
Object.keys(members).forEach((propName) => {
241241
const propData = members[propName];
242242
const isMethod = (<any[]>propData).some(a => a['__symbolic'] == 'method');
243-
methodNames[propName] = methodNames[propName] || isMethod;
243+
methodNames ![propName] = methodNames ![propName] || isMethod;
244244
});
245245
this.methodCache.set(type, methodNames);
246246
}
247247
return methodNames;
248248
}
249249

250-
private findParentType(type: StaticSymbol, classMetadata: any): StaticSymbol|null {
250+
private findParentType(type: StaticSymbol, classMetadata: any): StaticSymbol|undefined {
251251
const parentType = this.trySimplify(type, classMetadata['extends']);
252252
if (parentType instanceof StaticSymbol) {
253253
return parentType;

0 commit comments

Comments
 (0)