diff --git a/packages/compiler-cli/src/compiler_host.ts b/packages/compiler-cli/src/compiler_host.ts index 85d441ff3f..79f6ae535a 100644 --- a/packages/compiler-cli/src/compiler_host.ts +++ b/packages/compiler-cli/src/compiler_host.ts @@ -33,7 +33,7 @@ export class CompilerHost implements AotCompilerHost { private resolverCache = new Map(); private bundleIndexCache = new Map(); private bundleIndexNames = new Set(); - private moduleFileNames = new Map(); + private moduleFileNames = new Map(); protected resolveModuleNameHost: CompilerHostContext; constructor( @@ -71,7 +71,7 @@ export class CompilerHost implements AotCompilerHost { moduleNameToFileName(m: string, containingFile: string): string|null { const key = m + ':' + (containingFile || ''); - let result = this.moduleFileNames.get(key); + let result: string|null = this.moduleFileNames.get(key) || null; if (!result) { if (!containingFile || !containingFile.length) { if (m.indexOf('.') === 0) { @@ -183,7 +183,7 @@ export class CompilerHost implements AotCompilerHost { return sf; } - getMetadataFor(filePath: string): ModuleMetadata[] { + getMetadataFor(filePath: string): ModuleMetadata[]|undefined { if (!this.context.fileExists(filePath)) { // If the file doesn't exists then we cannot return metadata for the file. // This will occur if the user refernced a declared module for which no file @@ -263,6 +263,7 @@ export class CompilerHost implements AotCompilerHost { if (this.context.fileExists(filePath)) { return this.context.readFile(filePath); } + return null; } getOutputFileName(sourceFilePath: string): string { @@ -287,7 +288,7 @@ export class CompilerHost implements AotCompilerHost { calculateEmitPath(filePath: string): string { // Write codegen in a directory structure matching the sources. - let root = this.options.basePath; + let root = this.options.basePath !; for (const eachRootDir of this.options.rootDirs || []) { if (this.options.trace) { console.error(`Check if ${filePath} is under rootDirs element ${eachRootDir}`); @@ -373,7 +374,7 @@ export class ModuleResolutionHostAdapter extends CompilerHostContextAdapter impl constructor(private host: ts.ModuleResolutionHost) { super(); if (host.directoryExists) { - this.directoryExists = (directoryName: string) => host.directoryExists(directoryName); + this.directoryExists = (directoryName: string) => host.directoryExists !(directoryName); } } diff --git a/packages/compiler-cli/src/extract_i18n.ts b/packages/compiler-cli/src/extract_i18n.ts index a41fa4a1dd..c8aec764a0 100644 --- a/packages/compiler-cli/src/extract_i18n.ts +++ b/packages/compiler-cli/src/extract_i18n.ts @@ -23,7 +23,7 @@ function extract( ngOptions: tsc.AngularCompilerOptions, cliOptions: tsc.I18nExtractionCliOptions, program: ts.Program, host: ts.CompilerHost): Promise { return Extractor.create(ngOptions, program, host, cliOptions.locale) - .extract(cliOptions.i18nFormat, cliOptions.outFile); + .extract(cliOptions.i18nFormat !, cliOptions.outFile); } // Entry point diff --git a/packages/compiler-cli/src/ngtools_api.ts b/packages/compiler-cli/src/ngtools_api.ts index d602f6843a..9f34dcb8d2 100644 --- a/packages/compiler-cli/src/ngtools_api.ts +++ b/packages/compiler-cli/src/ngtools_api.ts @@ -92,9 +92,9 @@ export class NgTools_InternalApi_NG_2 { const hostContext: CompilerHostContext = new CustomLoaderModuleResolutionHostAdapter(options.readResource, options.host); const cliOptions: NgcCliOptions = { - i18nFormat: options.i18nFormat, - i18nFile: options.i18nFile, - locale: options.locale, + i18nFormat: options.i18nFormat !, + i18nFile: options.i18nFile !, + locale: options.locale !, basePath: options.basePath }; @@ -148,6 +148,6 @@ export class NgTools_InternalApi_NG_2 { const extractor = Extractor.create( options.angularCompilerOptions, options.program, options.host, locale, hostContext); - return extractor.extract(options.i18nFormat, options.outFile || null); + return extractor.extract(options.i18nFormat !, options.outFile || null); } } diff --git a/packages/compiler-cli/src/ngtools_impl.ts b/packages/compiler-cli/src/ngtools_impl.ts index 80be64a271..bbb8a72246 100644 --- a/packages/compiler-cli/src/ngtools_impl.ts +++ b/packages/compiler-cli/src/ngtools_impl.ts @@ -33,7 +33,8 @@ export type LazyRouteMap = { // A route definition. Normally the short form 'path/to/module#ModuleClassName' is used by // the user, and this is a helper class to extract information from it. export class RouteDef { - private constructor(public readonly path: string, public readonly className: string = null) {} + private constructor(public readonly path: string, public readonly className: string|null = null) { + } toString() { return (this.className === null || this.className == 'default') ? @@ -58,7 +59,7 @@ export function listLazyRoutesOfModule( const entryRouteDef = RouteDef.fromString(entryModule); const containingFile = _resolveModule(entryRouteDef.path, entryRouteDef.path, host); const modulePath = `./${containingFile.replace(/^(.*)\//, '')}`; - const className = entryRouteDef.className; + const className = entryRouteDef.className !; // List loadChildren of this single module. const appStaticSymbol = reflector.findDeclaration(modulePath, className, containingFile); diff --git a/packages/compiler-cli/src/path_mapped_compiler_host.ts b/packages/compiler-cli/src/path_mapped_compiler_host.ts index 6dcbf8cee5..2463b5b4ee 100644 --- a/packages/compiler-cli/src/path_mapped_compiler_host.ts +++ b/packages/compiler-cli/src/path_mapped_compiler_host.ts @@ -40,7 +40,7 @@ export class PathMappedCompilerHost extends CompilerHost { return fileName; } - moduleNameToFileName(m: string, containingFile: string) { + moduleNameToFileName(m: string, containingFile: string): string|null { if (!containingFile || !containingFile.length) { if (m.indexOf('.') === 0) { throw new Error('Resolution of relative paths requires a containing file.'); @@ -59,6 +59,7 @@ export class PathMappedCompilerHost extends CompilerHost { return this.getCanonicalFileName(resolved.resolvedFileName); } } + return null; } /** @@ -90,7 +91,7 @@ export class PathMappedCompilerHost extends CompilerHost { const importModuleName = importedFile.replace(EXT, ''); const parts = importModuleName.split(path.sep).filter(p => !!p); - let foundRelativeImport: string; + let foundRelativeImport: string = undefined !; for (let index = parts.length - 1; index >= 0; index--) { let candidate = parts.slice(index, parts.length).join(path.sep); if (resolvable(candidate)) { @@ -135,5 +136,6 @@ export class PathMappedCompilerHost extends CompilerHost { return metadata ? [metadata] : []; } } + return null !; } } diff --git a/packages/compiler-cli/tsconfig-build.json b/packages/compiler-cli/tsconfig-build.json index 173ee83cc5..05b1164765 100644 --- a/packages/compiler-cli/tsconfig-build.json +++ b/packages/compiler-cli/tsconfig-build.json @@ -4,6 +4,7 @@ "declaration": true, "experimentalDecorators": true, "noImplicitAny": true, + "strictNullChecks": true, "module": "commonjs", "outDir": "../../dist/packages/compiler-cli", "paths": { diff --git a/packages/compiler/src/aot/compiler.ts b/packages/compiler/src/aot/compiler.ts index 5aa11fd17b..2fd7aac5f8 100644 --- a/packages/compiler/src/aot/compiler.ts +++ b/packages/compiler/src/aot/compiler.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompileProviderMetadata, componentFactoryName, createHostComponentMeta, flatten, identifierName, sourceUrl, templateSourceUrl} from '../compile_metadata'; +import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompileProviderMetadata, CompileTypeSummary, componentFactoryName, createHostComponentMeta, flatten, identifierName, sourceUrl, templateSourceUrl} from '../compile_metadata'; import {CompilerConfig} from '../config'; import {Identifiers, createIdentifier, createIdentifierToken} from '../identifiers'; import {CompileMetadataResolver} from '../metadata_resolver'; @@ -32,8 +32,8 @@ export class AotCompiler { private _metadataResolver: CompileMetadataResolver, private _templateParser: TemplateParser, private _styleCompiler: StyleCompiler, private _viewCompiler: ViewCompiler, private _ngModuleCompiler: NgModuleCompiler, private _outputEmitter: OutputEmitter, - private _summaryResolver: SummaryResolver, private _localeId: string, - private _translationFormat: string, private _genFilePreamble: string, + private _summaryResolver: SummaryResolver, private _localeId: string|null, + private _translationFormat: string|null, private _genFilePreamble: string|null, private _symbolResolver: StaticSymbolResolver) {} clearCache() { this._metadataResolver.clearCache(); } @@ -113,11 +113,11 @@ export class AotCompiler { targetExportedVars: string[]): GeneratedFile { const symbolSummaries = this._symbolResolver.getSymbolsOf(srcFileUrl) .map(symbol => this._symbolResolver.resolveSymbol(symbol)); - const typeSummaries = [ - ...ngModules.map(ref => this._metadataResolver.getNgModuleSummary(ref)), - ...directives.map(ref => this._metadataResolver.getDirectiveSummary(ref)), - ...pipes.map(ref => this._metadataResolver.getPipeSummary(ref)), - ...injectables.map(ref => this._metadataResolver.getInjectableSummary(ref)) + const typeSummaries: CompileTypeSummary[] = [ + ...ngModules.map(ref => this._metadataResolver.getNgModuleSummary(ref) !), + ...directives.map(ref => this._metadataResolver.getDirectiveSummary(ref) !), + ...pipes.map(ref => this._metadataResolver.getPipeSummary(ref) !), + ...injectables.map(ref => this._metadataResolver.getInjectableSummary(ref) !) ]; const {json, exportAs} = serializeSummaries( this._summaryResolver, this._symbolResolver, symbolSummaries, typeSummaries); @@ -130,7 +130,7 @@ export class AotCompiler { } private _compileModule(ngModuleType: StaticSymbol, targetStatements: o.Statement[]): string { - const ngModule = this._metadataResolver.getNgModuleMetadata(ngModuleType); + const ngModule = this._metadataResolver.getNgModuleMetadata(ngModuleType) !; const providers: CompileProviderMetadata[] = []; if (this._localeId) { @@ -183,11 +183,11 @@ export class AotCompiler { o.variable(hostViewFactoryVar), new o.LiteralMapExpr(inputsExprs), new o.LiteralMapExpr(outputsExprs), o.literalArr( - compMeta.template.ngContentSelectors.map(selector => o.literal(selector))) + compMeta.template !.ngContentSelectors.map(selector => o.literal(selector))) ])) .toDeclStmt( o.importType( - createIdentifier(Identifiers.ComponentFactory), [o.importType(compMeta.type)], + createIdentifier(Identifiers.ComponentFactory), [o.importType(compMeta.type) !], [o.TypeModifier.Const]), [o.StmtModifier.Final])); return compFactoryVar; @@ -195,7 +195,7 @@ export class AotCompiler { private _compileComponent( compMeta: CompileDirectiveMetadata, ngModule: CompileNgModuleMetadata, - directiveIdentifiers: CompileIdentifierMetadata[], componentStyles: CompiledStylesheet, + directiveIdentifiers: CompileIdentifierMetadata[], componentStyles: CompiledStylesheet|null, fileSuffix: string, targetStatements: o.Statement[]): {viewClassVar: string, compRenderTypeVar: string} { const directives = @@ -204,8 +204,8 @@ export class AotCompiler { pipe => this._metadataResolver.getPipeSummary(pipe.reference)); const {template: parsedTemplate, pipes: usedPipes} = this._templateParser.parse( - compMeta, compMeta.template.template, directives, pipes, ngModule.schemas, - templateSourceUrl(ngModule.type, compMeta, compMeta.template)); + compMeta, compMeta.template !.template !, directives, pipes, ngModule.schemas, + templateSourceUrl(ngModule.type, compMeta, compMeta.template !)); const stylesExpr = componentStyles ? o.variable(componentStyles.stylesVar) : o.literalArr([]); const viewResult = this._viewCompiler.compileComponent(compMeta, parsedTemplate, stylesExpr, usedPipes); @@ -221,8 +221,9 @@ export class AotCompiler { fileUrl: string, stylesCompileResult: CompiledStylesheet, fileSuffix: string): GeneratedFile { _resolveStyleStatements(this._symbolResolver, stylesCompileResult, fileSuffix); return this._codegenSourceModule( - fileUrl, _stylesModuleUrl( - stylesCompileResult.meta.moduleUrl, stylesCompileResult.isShimmed, fileSuffix), + fileUrl, + _stylesModuleUrl( + stylesCompileResult.meta.moduleUrl !, stylesCompileResult.isShimmed, fileSuffix), stylesCompileResult.statements, [stylesCompileResult.stylesVar]); } diff --git a/packages/compiler/src/aot/compiler_factory.ts b/packages/compiler/src/aot/compiler_factory.ts index 56b7990416..7e21069a52 100644 --- a/packages/compiler/src/aot/compiler_factory.ts +++ b/packages/compiler/src/aot/compiler_factory.ts @@ -70,15 +70,16 @@ export function createAotCompiler(compilerHost: AotCompilerHost, options: AotCom console, symbolCache, staticReflector); // TODO(vicb): do not pass options.i18nFormat here const importResolver = { - getImportAs: (symbol: StaticSymbol) => symbolResolver.getImportAs(symbol), + getImportAs: (symbol: StaticSymbol) => symbolResolver.getImportAs(symbol) !, fileNameToModuleName: (fileName: string, containingFilePath: string) => compilerHost.fileNameToModuleName(fileName, containingFilePath), - getTypeArity: (symbol: StaticSymbol) => symbolResolver.getTypeArity(symbol) + getTypeArity: (symbol: StaticSymbol) => symbolResolver.getTypeArity(symbol) ! }; const viewCompiler = new ViewCompiler(config, elementSchemaRegistry); const compiler = new AotCompiler( config, compilerHost, resolver, tmplParser, new StyleCompiler(urlResolver), viewCompiler, new NgModuleCompiler(), new TypeScriptEmitter(importResolver), summaryResolver, - options.locale, options.i18nFormat, options.genFilePreamble, symbolResolver); + options.locale || null, options.i18nFormat || null, options.genFilePreamble || null, + symbolResolver); return {compiler, reflector: staticReflector}; } diff --git a/packages/compiler/src/aot/compiler_host.ts b/packages/compiler/src/aot/compiler_host.ts index f37558dc7f..f7a83970d8 100644 --- a/packages/compiler/src/aot/compiler_host.ts +++ b/packages/compiler/src/aot/compiler_host.ts @@ -20,8 +20,7 @@ export interface AotCompilerHost extends StaticSymbolResolverHost, AotSummaryRes * * See ImportResolver. */ - fileNameToModuleName(importedFilePath: string, containingFilePath: string): string - /*|null*/; + fileNameToModuleName(importedFilePath: string, containingFilePath: string): string|null; /** * Loads a resource (e.g. html / css) diff --git a/packages/compiler/src/aot/static_reflection_capabilities.ts b/packages/compiler/src/aot/static_reflection_capabilities.ts index 3031255938..4a11410ee9 100644 --- a/packages/compiler/src/aot/static_reflection_capabilities.ts +++ b/packages/compiler/src/aot/static_reflection_capabilities.ts @@ -41,7 +41,7 @@ export class StaticAndDynamicReflectionCapabilities { getter(name: string): ɵGetterFn { return this.dynamicDelegate.getter(name); } setter(name: string): ɵSetterFn { return this.dynamicDelegate.setter(name); } method(name: string): ɵMethodFn { return this.dynamicDelegate.method(name); } - importUri(type: any): string { return this.staticDelegate.importUri(type); } + importUri(type: any): string { return this.staticDelegate.importUri(type) !; } resourceUri(type: any): string { return this.staticDelegate.resourceUri(type); } resolveIdentifier(name: string, moduleUrl: string, members: string[], runtime: any) { return this.staticDelegate.resolveIdentifier(name, moduleUrl, members); diff --git a/packages/compiler/src/aot/static_reflector.ts b/packages/compiler/src/aot/static_reflector.ts index 513252b8d5..bb97bd1676 100644 --- a/packages/compiler/src/aot/static_reflector.ts +++ b/packages/compiler/src/aot/static_reflector.ts @@ -47,7 +47,7 @@ export class StaticReflector implements ɵReflectorReader { private symbolResolver: StaticSymbolResolver, knownMetadataClasses: {name: string, filePath: string, ctor: any}[] = [], knownMetadataFunctions: {name: string, filePath: string, fn: any}[] = [], - private errorRecorder?: (error: any, fileName: string) => void) { + private errorRecorder?: (error: any, fileName?: string) => void) { this.initializeConversionMap(); knownMetadataClasses.forEach( (kc) => this._registerDecoratorOrConstructor( @@ -67,7 +67,7 @@ export class StaticReflector implements ɵReflectorReader { this.annotationNames.set(Injectable, 'Injectable'); } - importUri(typeOrFunc: StaticSymbol): string { + importUri(typeOrFunc: StaticSymbol): string|null { const staticSymbol = this.findSymbolDeclaration(typeOrFunc); return staticSymbol ? staticSymbol.filePath : null; } @@ -129,14 +129,14 @@ export class StaticReflector implements ɵReflectorReader { const summary = this.summaryResolver.resolveSummary(parentType); if (summary && summary.type) { const requiredAnnotationTypes = - this.annotationForParentClassWithSummaryKind.get(summary.type.summaryKind); + this.annotationForParentClassWithSummaryKind.get(summary.type.summaryKind !) !; const typeHasRequiredAnnotation = requiredAnnotationTypes.some( - requiredType => ownAnnotations.some(ann => ann instanceof requiredType)); + (requiredType: any) => ownAnnotations.some(ann => ann instanceof requiredType)); if (!typeHasRequiredAnnotation) { this.reportError( syntaxError( - `Class ${type.name} in ${type.filePath} extends from a ${CompileSummaryKind[summary.type.summaryKind]} in another compilation unit without duplicating the decorator. ` + - `Please add a ${requiredAnnotationTypes.map(type => this.annotationNames.get(type)).join(' or ')} decorator to the class.`), + `Class ${type.name} in ${type.filePath} extends from a ${CompileSummaryKind[summary.type.summaryKind!]} in another compilation unit without duplicating the decorator. ` + + `Please add a ${requiredAnnotationTypes.map((type: any) => this.annotationNames.get(type)).join(' or ')} decorator to the class.`), type); } } @@ -155,7 +155,7 @@ export class StaticReflector implements ɵReflectorReader { if (parentType) { const parentPropMetadata = this.propMetadata(parentType); Object.keys(parentPropMetadata).forEach((parentProp) => { - propMetadata[parentProp] = parentPropMetadata[parentProp]; + propMetadata ![parentProp] = parentPropMetadata[parentProp]; }); } @@ -165,10 +165,10 @@ export class StaticReflector implements ɵReflectorReader { const prop = (propData) .find(a => a['__symbolic'] == 'property' || a['__symbolic'] == 'method'); const decorators: any[] = []; - if (propMetadata[propName]) { - decorators.push(...propMetadata[propName]); + if (propMetadata ![propName]) { + decorators.push(...propMetadata ![propName]); } - propMetadata[propName] = decorators; + propMetadata ![propName] = decorators; if (prop && prop['decorators']) { decorators.push(...this.simplify(type, prop['decorators'])); } @@ -206,7 +206,7 @@ export class StaticReflector implements ɵReflectorReader { if (decorators) { nestedResult.push(...decorators); } - parameters.push(nestedResult); + parameters !.push(nestedResult); }); } else if (parentType) { parameters = this.parameters(parentType); @@ -232,7 +232,7 @@ export class StaticReflector implements ɵReflectorReader { if (parentType) { const parentMethodNames = this._methodNames(parentType); Object.keys(parentMethodNames).forEach((parentProp) => { - methodNames[parentProp] = parentMethodNames[parentProp]; + methodNames ![parentProp] = parentMethodNames[parentProp]; }); } @@ -240,14 +240,14 @@ export class StaticReflector implements ɵReflectorReader { Object.keys(members).forEach((propName) => { const propData = members[propName]; const isMethod = (propData).some(a => a['__symbolic'] == 'method'); - methodNames[propName] = methodNames[propName] || isMethod; + methodNames ![propName] = methodNames ![propName] || isMethod; }); this.methodCache.set(type, methodNames); } return methodNames; } - private findParentType(type: StaticSymbol, classMetadata: any): StaticSymbol|null { + private findParentType(type: StaticSymbol, classMetadata: any): StaticSymbol|undefined { const parentType = this.trySimplify(type, classMetadata['extends']); if (parentType instanceof StaticSymbol) { return parentType; diff --git a/packages/compiler/src/aot/static_symbol_resolver.ts b/packages/compiler/src/aot/static_symbol_resolver.ts index 7135f6f744..8e0f645869 100644 --- a/packages/compiler/src/aot/static_symbol_resolver.ts +++ b/packages/compiler/src/aot/static_symbol_resolver.ts @@ -31,14 +31,14 @@ export interface StaticSymbolResolverHost { * @param modulePath is a string identifier for a module as an absolute path. * @returns the metadata for the given module. */ - getMetadataFor(modulePath: string): {[key: string]: any}[]; + getMetadataFor(modulePath: string): {[key: string]: any}[]|undefined; /** * Converts a module name that is used in an `import` to a file path. * I.e. * `path/to/containingFile.ts` containing `import {...} from 'module-name'`. */ - moduleNameToFileName(moduleName: string, containingFile: string): string /*|null*/; + moduleNameToFileName(moduleName: string, containingFile?: string): string|null; } const SUPPORTED_SCHEMA_VERSION = 3; @@ -64,17 +64,17 @@ export class StaticSymbolResolver { constructor( private host: StaticSymbolResolverHost, private staticSymbolCache: StaticSymbolCache, private summaryResolver: SummaryResolver, - private errorRecorder?: (error: any, fileName: string) => void) {} + private errorRecorder?: (error: any, fileName?: string) => void) {} resolveSymbol(staticSymbol: StaticSymbol): ResolvedStaticSymbol { if (staticSymbol.members.length > 0) { - return this._resolveSymbolMembers(staticSymbol); + return this._resolveSymbolMembers(staticSymbol) !; } let result = this.resolvedSymbols.get(staticSymbol); if (result) { return result; } - result = this._resolveSymbolFromSummary(staticSymbol); + result = this._resolveSymbolFromSummary(staticSymbol) !; if (result) { return result; } @@ -82,7 +82,7 @@ export class StaticSymbolResolver { // have summaries, only .d.ts files. So we always need to check both, the summary // and metadata. this._createSymbolsOf(staticSymbol.filePath); - result = this.resolvedSymbols.get(staticSymbol); + result = this.resolvedSymbols.get(staticSymbol) !; return result; } @@ -95,7 +95,7 @@ export class StaticSymbolResolver { * * @param staticSymbol the symbol for which to generate a import symbol */ - getImportAs(staticSymbol: StaticSymbol): StaticSymbol { + getImportAs(staticSymbol: StaticSymbol): StaticSymbol|null { if (staticSymbol.members.length) { const baseSymbol = this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name); const baseImportAs = this.getImportAs(baseSymbol); @@ -105,7 +105,7 @@ export class StaticSymbolResolver { } let result = this.summaryResolver.getImportAs(staticSymbol); if (!result) { - result = this.importAs.get(staticSymbol); + result = this.importAs.get(staticSymbol) !; } return result; } @@ -123,7 +123,7 @@ export class StaticSymbolResolver { * getTypeArity returns the number of generic type parameters the given symbol * has. If the symbol is not a type the result is null. */ - getTypeArity(staticSymbol: StaticSymbol): number /*|null*/ { + getTypeArity(staticSymbol: StaticSymbol): number|null { // If the file is a factory file, don't resolve the symbol as doing so would // cause the metadata for an factory file to be loaded which doesn't exist. // All references to generated classes must include the correct arity whenever @@ -163,7 +163,7 @@ export class StaticSymbolResolver { } } - private _resolveSymbolMembers(staticSymbol: StaticSymbol): ResolvedStaticSymbol { + private _resolveSymbolMembers(staticSymbol: StaticSymbol): ResolvedStaticSymbol|null { const members = staticSymbol.members; const baseResolvedSymbol = this.resolveSymbol(this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name)); @@ -188,7 +188,7 @@ export class StaticSymbolResolver { return null; } - private _resolveSymbolFromSummary(staticSymbol: StaticSymbol): ResolvedStaticSymbol { + private _resolveSymbolFromSummary(staticSymbol: StaticSymbol): ResolvedStaticSymbol|null { const summary = this.summaryResolver.resolveSummary(staticSymbol); return summary ? new ResolvedStaticSymbol(staticSymbol, summary.metadata) : null; } @@ -252,7 +252,7 @@ export class StaticSymbolResolver { const originFilePath = this.resolveModule(origin, filePath); if (!originFilePath) { this.reportError( - new Error(`Couldn't resolve original symbol for ${origin} from ${filePath}`), null); + new Error(`Couldn't resolve original symbol for ${origin} from ${filePath}`)); } else { this.symbolResourcePaths.set(symbol, originFilePath); } @@ -337,7 +337,7 @@ export class StaticSymbolResolver { } let filePath: string; if (module) { - filePath = self.resolveModule(module, sourceSymbol.filePath); + filePath = self.resolveModule(module, sourceSymbol.filePath) !; if (!filePath) { return { __symbolic: 'error', @@ -381,7 +381,7 @@ export class StaticSymbolResolver { return new ResolvedStaticSymbol(sourceSymbol, targetSymbol); } - private reportError(error: Error, context: StaticSymbol, path?: string) { + private reportError(error: Error, context?: StaticSymbol, path?: string) { if (this.errorRecorder) { this.errorRecorder(error, (context && context.filePath) || path); } else { @@ -413,7 +413,7 @@ export class StaticSymbolResolver { const errorMessage = moduleMetadata['version'] == 2 ? `Unsupported metadata version ${moduleMetadata['version']} for module ${module}. This module should be compiled with a newer version of ngc` : `Metadata version mismatch for module ${module}, found version ${moduleMetadata['version']}, expected ${SUPPORTED_SCHEMA_VERSION}`; - this.reportError(new Error(errorMessage), null); + this.reportError(new Error(errorMessage)); } this.metadataCache.set(module, moduleMetadata); } @@ -426,20 +426,20 @@ export class StaticSymbolResolver { this.reportError( new Error(`Could not resolve module ${module}${containingFile ? ` relative to $ { containingFile - } `: ''}`), - null); + } `: ''}`)); return this.getStaticSymbol(`ERROR:${module}`, symbolName); } return this.getStaticSymbol(filePath, symbolName); } - private resolveModule(module: string, containingFile: string): string { + private resolveModule(module: string, containingFile?: string): string|null { try { return this.host.moduleNameToFileName(module, containingFile); } catch (e) { console.error(`Could not resolve module '${module}' relative to file ${containingFile}`); - this.reportError(e, null, containingFile); + this.reportError(e, undefined, containingFile); } + return null; } } @@ -447,4 +447,4 @@ export class StaticSymbolResolver { // See https://github.com/Microsoft/TypeScript/blob/master/src/compiler/utilities.ts export function unescapeIdentifier(identifier: string): string { return identifier.startsWith('___') ? identifier.substr(1) : identifier; -} \ No newline at end of file +} diff --git a/packages/compiler/src/aot/summary_resolver.ts b/packages/compiler/src/aot/summary_resolver.ts index 98a589860b..c42e810906 100644 --- a/packages/compiler/src/aot/summary_resolver.ts +++ b/packages/compiler/src/aot/summary_resolver.ts @@ -16,7 +16,7 @@ export interface AotSummaryResolverHost { /** * Loads an NgModule/Directive/Pipe summary file */ - loadSummary(filePath: string): string /*|null*/; + loadSummary(filePath: string): string|null; /** * Returns whether a file is a source file or not. @@ -53,7 +53,7 @@ export class AotSummaryResolver implements SummaryResolver { let summary = this.summaryCache.get(staticSymbol); if (!summary) { this._loadSummaryFile(staticSymbol.filePath); - summary = this.summaryCache.get(staticSymbol); + summary = this.summaryCache.get(staticSymbol) !; } return summary; } @@ -65,7 +65,7 @@ export class AotSummaryResolver implements SummaryResolver { getImportAs(staticSymbol: StaticSymbol): StaticSymbol { staticSymbol.assertNoMembers(); - return this.importAs.get(staticSymbol); + return this.importAs.get(staticSymbol) !; } private _loadSummaryFile(filePath: string) { @@ -75,7 +75,7 @@ export class AotSummaryResolver implements SummaryResolver { this.loadedFilePaths.add(filePath); if (this.isLibraryFile(filePath)) { const summaryFilePath = summaryFileName(filePath); - let json: string; + let json: string|null; try { json = this.host.loadSummary(summaryFilePath); } catch (e) { diff --git a/packages/compiler/src/aot/summary_serializer.ts b/packages/compiler/src/aot/summary_serializer.ts index 81bcae1458..75e0d0b365 100644 --- a/packages/compiler/src/aot/summary_serializer.ts +++ b/packages/compiler/src/aot/summary_serializer.ts @@ -133,7 +133,7 @@ class Serializer extends ValueTransformer { summaries: this.processedSummaries, symbols: this.symbols.map((symbol, index) => { symbol.assertNoMembers(); - let importAs: string; + let importAs: string = undefined !; if (this.summaryResolver.isLibraryFile(symbol.filePath)) { importAs = `${symbol.name}_${index}`; exportAs.push({symbol, exportAs: importAs}); diff --git a/packages/compiler/src/compile_metadata.ts b/packages/compiler/src/compile_metadata.ts index eac362f4ac..ea0d1f4ea2 100644 --- a/packages/compiler/src/compile_metadata.ts +++ b/packages/compiler/src/compile_metadata.ts @@ -22,7 +22,8 @@ const HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/; export class CompileAnimationEntryMetadata { constructor( - public name: string = null, public definitions: CompileAnimationStateMetadata[] = null) {} + public name: string|null = null, + public definitions: CompileAnimationStateMetadata[]|null = null) {} } export abstract class CompileAnimationStateMetadata {} @@ -49,7 +50,8 @@ export class CompileAnimationKeyframesSequenceMetadata extends CompileAnimationM export class CompileAnimationStyleMetadata extends CompileAnimationMetadata { constructor( - public offset: number, public styles: Array = null) { + public offset: number, + public styles: Array|null = null) { super(); } } @@ -57,21 +59,21 @@ export class CompileAnimationStyleMetadata extends CompileAnimationMetadata { export class CompileAnimationAnimateMetadata extends CompileAnimationMetadata { constructor( public timings: string|number = 0, public styles: CompileAnimationStyleMetadata| - CompileAnimationKeyframesSequenceMetadata = null) { + CompileAnimationKeyframesSequenceMetadata|null = null) { super(); } } export abstract class CompileAnimationWithStepsMetadata extends CompileAnimationMetadata { - constructor(public steps: CompileAnimationMetadata[] = null) { super(); } + constructor(public steps: CompileAnimationMetadata[]|null = null) { super(); } } export class CompileAnimationSequenceMetadata extends CompileAnimationWithStepsMetadata { - constructor(steps: CompileAnimationMetadata[] = null) { super(steps); } + constructor(steps: CompileAnimationMetadata[]|null = null) { super(steps); } } export class CompileAnimationGroupMetadata extends CompileAnimationWithStepsMetadata { - constructor(steps: CompileAnimationMetadata[] = null) { super(steps); } + constructor(steps: CompileAnimationMetadata[]|null = null) { super(steps); } } @@ -81,7 +83,8 @@ function _sanitizeIdentifier(name: string): string { let _anonymousTypeIndex = 0; -export function identifierName(compileIdentifier: CompileIdentifierMetadata): string { +export function identifierName(compileIdentifier: CompileIdentifierMetadata | null | undefined): + string|null { if (!compileIdentifier || !compileIdentifier.reference) { return null; } @@ -148,7 +151,7 @@ export enum CompileSummaryKind { * the directive / module itself. */ export interface CompileTypeSummary { - summaryKind: CompileSummaryKind; + summaryKind: CompileSummaryKind|null; type: CompileTypeMetadata; } @@ -216,13 +219,13 @@ export interface CompileQueryMetadata { * Metadata about a stylesheet */ export class CompileStylesheetMetadata { - moduleUrl: string; + moduleUrl: string|null; styles: string[]; styleUrls: string[]; constructor( {moduleUrl, styles, styleUrls}: {moduleUrl?: string, styles?: string[], styleUrls?: string[]} = {}) { - this.moduleUrl = moduleUrl; + this.moduleUrl = moduleUrl || null; this.styles = _normalizeArray(styles); this.styleUrls = _normalizeArray(styleUrls); } @@ -232,39 +235,38 @@ export class CompileStylesheetMetadata { * Summary Metadata regarding compilation of a template. */ export interface CompileTemplateSummary { - animations: string[]; + animations: string[]|null; ngContentSelectors: string[]; - encapsulation: ViewEncapsulation; + encapsulation: ViewEncapsulation|null; } /** * Metadata regarding compilation of a template. */ export class CompileTemplateMetadata { - encapsulation: ViewEncapsulation; - template: string; - templateUrl: string; + encapsulation: ViewEncapsulation|null; + template: string|null; + templateUrl: string|null; isInline: boolean; styles: string[]; styleUrls: string[]; externalStylesheets: CompileStylesheetMetadata[]; animations: any[]; ngContentSelectors: string[]; - interpolation: [string, string]; - constructor( - {encapsulation, template, templateUrl, styles, styleUrls, externalStylesheets, animations, - ngContentSelectors, interpolation, isInline}: { - encapsulation?: ViewEncapsulation, - template?: string, - templateUrl?: string, - styles?: string[], - styleUrls?: string[], - externalStylesheets?: CompileStylesheetMetadata[], - ngContentSelectors?: string[], - animations?: any[], - interpolation?: [string, string], - isInline?: boolean - } = {}) { + interpolation: [string, string]|null; + constructor({encapsulation, template, templateUrl, styles, styleUrls, externalStylesheets, + animations, ngContentSelectors, interpolation, isInline}: { + encapsulation: ViewEncapsulation | null, + template: string|null, + templateUrl: string|null, + styles: string[], + styleUrls: string[], + externalStylesheets: CompileStylesheetMetadata[], + ngContentSelectors: string[], + animations: any[], + interpolation: [string, string]|null, + isInline: boolean + }) { this.encapsulation = encapsulation; this.template = template; this.templateUrl = templateUrl; @@ -299,8 +301,8 @@ export interface CompileEntryComponentMetadata { export interface CompileDirectiveSummary extends CompileTypeSummary { type: CompileTypeMetadata; isComponent: boolean; - selector: string; - exportAs: string; + selector: string|null; + exportAs: string|null; inputs: {[key: string]: string}; outputs: {[key: string]: string}; hostListeners: {[key: string]: string}; @@ -311,40 +313,39 @@ export interface CompileDirectiveSummary extends CompileTypeSummary { queries: CompileQueryMetadata[]; viewQueries: CompileQueryMetadata[]; entryComponents: CompileEntryComponentMetadata[]; - changeDetection: ChangeDetectionStrategy; - template: CompileTemplateSummary; - componentViewType: StaticSymbol|ProxyClass; - rendererType: StaticSymbol|RendererType2; - componentFactory: StaticSymbol|ComponentFactory; + changeDetection: ChangeDetectionStrategy|null; + template: CompileTemplateSummary|null; + componentViewType: StaticSymbol|ProxyClass|null; + rendererType: StaticSymbol|RendererType2|null; + componentFactory: StaticSymbol|ComponentFactory|null; } /** * Metadata regarding compilation of a directive. */ export class CompileDirectiveMetadata { - static create( - {isHost, type, isComponent, selector, exportAs, changeDetection, inputs, outputs, host, - providers, viewProviders, queries, viewQueries, entryComponents, template, componentViewType, - rendererType, componentFactory}: { - isHost?: boolean, - type?: CompileTypeMetadata, - isComponent?: boolean, - selector?: string, - exportAs?: string, - changeDetection?: ChangeDetectionStrategy, - inputs?: string[], - outputs?: string[], - host?: {[key: string]: string}, - providers?: CompileProviderMetadata[], - viewProviders?: CompileProviderMetadata[], - queries?: CompileQueryMetadata[], - viewQueries?: CompileQueryMetadata[], - entryComponents?: CompileEntryComponentMetadata[], - template?: CompileTemplateMetadata, - componentViewType?: StaticSymbol|ProxyClass, - rendererType?: StaticSymbol|RendererType2, - componentFactory?: StaticSymbol|ComponentFactory, - } = {}): CompileDirectiveMetadata { + static create({isHost, type, isComponent, selector, exportAs, changeDetection, inputs, outputs, + host, providers, viewProviders, queries, viewQueries, entryComponents, template, + componentViewType, rendererType, componentFactory}: { + isHost: boolean, + type: CompileTypeMetadata, + isComponent: boolean, + selector: string|null, + exportAs: string|null, + changeDetection: ChangeDetectionStrategy|null, + inputs: string[], + outputs: string[], + host: {[key: string]: string}, + providers: CompileProviderMetadata[], + viewProviders: CompileProviderMetadata[], + queries: CompileQueryMetadata[], + viewQueries: CompileQueryMetadata[], + entryComponents: CompileEntryComponentMetadata[], + template: CompileTemplateMetadata, + componentViewType: StaticSymbol|ProxyClass|null, + rendererType: StaticSymbol|RendererType2|null, + componentFactory: StaticSymbol|ComponentFactory|null, + }): CompileDirectiveMetadata { const hostListeners: {[key: string]: string} = {}; const hostProperties: {[key: string]: string} = {}; const hostAttributes: {[key: string]: string} = {}; @@ -403,9 +404,9 @@ export class CompileDirectiveMetadata { isHost: boolean; type: CompileTypeMetadata; isComponent: boolean; - selector: string; - exportAs: string; - changeDetection: ChangeDetectionStrategy; + selector: string|null; + exportAs: string|null; + changeDetection: ChangeDetectionStrategy|null; inputs: {[key: string]: string}; outputs: {[key: string]: string}; hostListeners: {[key: string]: string}; @@ -417,37 +418,37 @@ export class CompileDirectiveMetadata { viewQueries: CompileQueryMetadata[]; entryComponents: CompileEntryComponentMetadata[]; - template: CompileTemplateMetadata; + template: CompileTemplateMetadata|null; - componentViewType: StaticSymbol|ProxyClass; - rendererType: StaticSymbol|RendererType2; - componentFactory: StaticSymbol|ComponentFactory; + componentViewType: StaticSymbol|ProxyClass|null; + rendererType: StaticSymbol|RendererType2|null; + componentFactory: StaticSymbol|ComponentFactory|null; constructor({isHost, type, isComponent, selector, exportAs, changeDetection, inputs, outputs, hostListeners, hostProperties, hostAttributes, providers, viewProviders, queries, viewQueries, entryComponents, template, componentViewType, rendererType, componentFactory}: { - isHost?: boolean, - type?: CompileTypeMetadata, - isComponent?: boolean, - selector?: string, - exportAs?: string, - changeDetection?: ChangeDetectionStrategy, - inputs?: {[key: string]: string}, - outputs?: {[key: string]: string}, - hostListeners?: {[key: string]: string}, - hostProperties?: {[key: string]: string}, - hostAttributes?: {[key: string]: string}, - providers?: CompileProviderMetadata[], - viewProviders?: CompileProviderMetadata[], - queries?: CompileQueryMetadata[], - viewQueries?: CompileQueryMetadata[], - entryComponents?: CompileEntryComponentMetadata[], - template?: CompileTemplateMetadata, - componentViewType?: StaticSymbol|ProxyClass, - rendererType?: StaticSymbol|RendererType2, - componentFactory?: StaticSymbol|ComponentFactory, - } = {}) { + isHost: boolean, + type: CompileTypeMetadata, + isComponent: boolean, + selector: string|null, + exportAs: string|null, + changeDetection: ChangeDetectionStrategy|null, + inputs: {[key: string]: string}, + outputs: {[key: string]: string}, + hostListeners: {[key: string]: string}, + hostProperties: {[key: string]: string}, + hostAttributes: {[key: string]: string}, + providers: CompileProviderMetadata[], + viewProviders: CompileProviderMetadata[], + queries: CompileQueryMetadata[], + viewQueries: CompileQueryMetadata[], + entryComponents: CompileEntryComponentMetadata[], + template: CompileTemplateMetadata|null, + componentViewType: StaticSymbol|ProxyClass|null, + rendererType: StaticSymbol|RendererType2|null, + componentFactory: StaticSymbol|ComponentFactory|null, + }) { this.isHost = !!isHost; this.type = type; this.isComponent = isComponent; @@ -503,7 +504,7 @@ export class CompileDirectiveMetadata { export function createHostComponentMeta( hostTypeReference: any, compMeta: CompileDirectiveMetadata, hostViewType: StaticSymbol | ProxyClass): CompileDirectiveMetadata { - const template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate(); + const template = CssSelector.parse(compMeta.selector !)[0].getMatchingElementTemplate(); return CompileDirectiveMetadata.create({ isHost: true, type: {reference: hostTypeReference, diDeps: [], lifecycleHooks: []}, @@ -516,7 +517,10 @@ export function createHostComponentMeta( ngContentSelectors: [], animations: [], isInline: true, + externalStylesheets: [], + interpolation: null }), + exportAs: null, changeDetection: ChangeDetectionStrategy.Default, inputs: [], outputs: [], @@ -528,7 +532,9 @@ export function createHostComponentMeta( queries: [], viewQueries: [], componentViewType: hostViewType, - rendererType: {id: '__Host__', encapsulation: ViewEncapsulation.None, styles: [], data: {}} + rendererType: {id: '__Host__', encapsulation: ViewEncapsulation.None, styles: [], data: {}}, + entryComponents: [], + componentFactory: null }); } @@ -544,10 +550,10 @@ export class CompilePipeMetadata { pure: boolean; constructor({type, name, pure}: { - type?: CompileTypeMetadata, - name?: string, - pure?: boolean, - } = {}) { + type: CompileTypeMetadata, + name: string, + pure: boolean, + }) { this.type = type; this.name = name; this.pure = !!pure; @@ -598,29 +604,28 @@ export class CompileNgModuleMetadata { importedModules: CompileNgModuleSummary[]; exportedModules: CompileNgModuleSummary[]; schemas: SchemaMetadata[]; - id: string; + id: string|null; transitiveModule: TransitiveCompileNgModuleMetadata; - constructor( - {type, providers, declaredDirectives, exportedDirectives, declaredPipes, exportedPipes, - entryComponents, bootstrapComponents, importedModules, exportedModules, schemas, - transitiveModule, id}: { - type?: CompileTypeMetadata, - providers?: CompileProviderMetadata[], - declaredDirectives?: CompileIdentifierMetadata[], - exportedDirectives?: CompileIdentifierMetadata[], - declaredPipes?: CompileIdentifierMetadata[], - exportedPipes?: CompileIdentifierMetadata[], - entryComponents?: CompileEntryComponentMetadata[], - bootstrapComponents?: CompileIdentifierMetadata[], - importedModules?: CompileNgModuleSummary[], - exportedModules?: CompileNgModuleSummary[], - transitiveModule?: TransitiveCompileNgModuleMetadata, - schemas?: SchemaMetadata[], - id?: string - } = {}) { - this.type = type; + constructor({type, providers, declaredDirectives, exportedDirectives, declaredPipes, + exportedPipes, entryComponents, bootstrapComponents, importedModules, + exportedModules, schemas, transitiveModule, id}: { + type: CompileTypeMetadata, + providers: CompileProviderMetadata[], + declaredDirectives: CompileIdentifierMetadata[], + exportedDirectives: CompileIdentifierMetadata[], + declaredPipes: CompileIdentifierMetadata[], + exportedPipes: CompileIdentifierMetadata[], + entryComponents: CompileEntryComponentMetadata[], + bootstrapComponents: CompileIdentifierMetadata[], + importedModules: CompileNgModuleSummary[], + exportedModules: CompileNgModuleSummary[], + transitiveModule: TransitiveCompileNgModuleMetadata, + schemas: SchemaMetadata[], + id: string|null + }) { + this.type = type || null; this.declaredDirectives = _normalizeArray(declaredDirectives); this.exportedDirectives = _normalizeArray(exportedDirectives); this.declaredPipes = _normalizeArray(declaredPipes); @@ -631,19 +636,20 @@ export class CompileNgModuleMetadata { this.importedModules = _normalizeArray(importedModules); this.exportedModules = _normalizeArray(exportedModules); this.schemas = _normalizeArray(schemas); - this.id = id; - this.transitiveModule = transitiveModule; + this.id = id || null; + this.transitiveModule = transitiveModule || null; } toSummary(): CompileNgModuleSummary { + const module = this.transitiveModule !; return { summaryKind: CompileSummaryKind.NgModule, type: this.type, - entryComponents: this.transitiveModule.entryComponents, - providers: this.transitiveModule.providers, - modules: this.transitiveModule.modules, - exportedDirectives: this.transitiveModule.exportedDirectives, - exportedPipes: this.transitiveModule.exportedPipes + entryComponents: module.entryComponents, + providers: module.providers, + modules: module.modules, + exportedDirectives: module.exportedDirectives, + exportedPipes: module.exportedPipes }; } } @@ -706,33 +712,33 @@ export class TransitiveCompileNgModuleMetadata { } } -function _normalizeArray(obj: any[]): any[] { +function _normalizeArray(obj: any[] | undefined | null): any[] { return obj || []; } export class ProviderMeta { token: any; - useClass: Type; + useClass: Type|null; useValue: any; useExisting: any; - useFactory: Function; - dependencies: Object[]; + useFactory: Function|null; + dependencies: Object[]|null; multi: boolean; constructor(token: any, {useClass, useValue, useExisting, useFactory, deps, multi}: { useClass?: Type, useValue?: any, useExisting?: any, - useFactory?: Function, - deps?: Object[], + useFactory?: Function|null, + deps?: Object[]|null, multi?: boolean }) { this.token = token; - this.useClass = useClass; + this.useClass = useClass || null; this.useValue = useValue; this.useExisting = useExisting; - this.useFactory = useFactory; - this.dependencies = deps; + this.useFactory = useFactory || null; + this.dependencies = deps || null; this.multi = !!multi; } } @@ -752,7 +758,7 @@ export function sourceUrl(url: string) { export function templateSourceUrl( ngModuleType: CompileIdentifierMetadata, compMeta: {type: CompileIdentifierMetadata}, - templateMeta: {isInline: boolean, templateUrl: string}) { + templateMeta: {isInline: boolean, templateUrl: string | null}) { let url: string; if (templateMeta.isInline) { if (compMeta.type.reference instanceof StaticSymbol) { @@ -763,7 +769,7 @@ export function templateSourceUrl( url = `${identifierName(ngModuleType)}/${identifierName(compMeta.type)}.html`; } } else { - url = templateMeta.templateUrl; + url = templateMeta.templateUrl !; } // always prepend ng:// to make angular resources easy to find and not clobber // user resources. @@ -771,7 +777,7 @@ export function templateSourceUrl( } export function sharedStylesheetJitUrl(meta: CompileStylesheetMetadata, id: number) { - const pathParts = meta.moduleUrl.split(/\/\\/g); + const pathParts = meta.moduleUrl !.split(/\/\\/g); const baseName = pathParts[pathParts.length - 1]; return sourceUrl(`css/${id}${baseName}.ngstyle.js`); } diff --git a/packages/compiler/src/compiler_util/expression_converter.ts b/packages/compiler/src/compiler_util/expression_converter.ts index 5fd971abb6..2a3350e8b8 100644 --- a/packages/compiler/src/compiler_util/expression_converter.ts +++ b/packages/compiler/src/compiler_util/expression_converter.ts @@ -13,7 +13,7 @@ import * as o from '../output/output_ast'; export class EventHandlerVars { static event = o.variable('$event'); } -export interface LocalResolver { getLocal(name: string): o.Expression; } +export interface LocalResolver { getLocal(name: string): o.Expression|null; } export class ConvertActionBindingResult { constructor(public stmts: o.Statement[], public allowDefault: o.ReadVarExpr) {} @@ -24,7 +24,7 @@ export class ConvertActionBindingResult { * used in an action binding (e.g. an event handler). */ export function convertActionBinding( - localResolver: LocalResolver, implicitReceiver: o.Expression, action: cdAst.AST, + localResolver: LocalResolver | null, implicitReceiver: o.Expression, action: cdAst.AST, bindingId: string): ConvertActionBindingResult { if (!localResolver) { localResolver = new DefaultLocalResolver(); @@ -51,7 +51,7 @@ export function convertActionBinding( flattenStatements(actionWithoutBuiltins.visit(visitor, _Mode.Statement), actionStmts); prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts); const lastIndex = actionStmts.length - 1; - let preventDefaultVar: o.ReadVarExpr = null; + let preventDefaultVar: o.ReadVarExpr = null !; if (lastIndex >= 0) { const lastStatement = actionStmts[lastIndex]; const returnExpr = convertStmtIntoExpression(lastStatement); @@ -90,7 +90,7 @@ export class ConvertPropertyBindingResult { * `convertPropertyBindingBuiltins`. */ export function convertPropertyBinding( - localResolver: LocalResolver, implicitReceiver: o.Expression, + localResolver: LocalResolver | null, implicitReceiver: o.Expression, expressionWithoutBuiltins: cdAst.AST, bindingId: string): ConvertPropertyBindingResult { if (!localResolver) { localResolver = new DefaultLocalResolver(); @@ -266,7 +266,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor { if (ast instanceof BuiltinFunctionCall) { fnResult = ast.converter(convertedArgs); } else { - fnResult = this.visit(ast.target, _Mode.Expression).callFn(convertedArgs); + fnResult = this.visit(ast.target !, _Mode.Expression).callFn(convertedArgs); } return convertToStatementIfNeeded(mode, fnResult); } @@ -321,7 +321,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor { return convertToStatementIfNeeded(mode, o.literal(ast.value)); } - private _getLocal(name: string): o.Expression { return this._localResolver.getLocal(name); } + private _getLocal(name: string): o.Expression|null { return this._localResolver.getLocal(name); } visitMethodCall(ast: cdAst.MethodCall, mode: _Mode): any { const leftMostSafe = this.leftMostSafeNode(ast); @@ -439,7 +439,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor { // which comes in as leftMostSafe to this routine. let guardedExpression = this.visit(leftMostSafe.receiver, _Mode.Expression); - let temporary: o.ReadVarExpr; + let temporary: o.ReadVarExpr = undefined !; if (this.needsTemporary(leftMostSafe.receiver)) { // If the expression has method calls or pipes then we need to save the result into a // temporary variable to avoid calling stateful or impure code more than once. @@ -577,7 +577,7 @@ function flattenStatements(arg: any, output: o.Statement[]) { } class DefaultLocalResolver implements LocalResolver { - getLocal(name: string): o.Expression { + getLocal(name: string): o.Expression|null { if (name === EventHandlerVars.event.name) { return EventHandlerVars.event; } @@ -593,7 +593,7 @@ function createPreventDefaultVar(bindingId: string): o.ReadVarExpr { return o.variable(`pd_${bindingId}`); } -function convertStmtIntoExpression(stmt: o.Statement): o.Expression { +function convertStmtIntoExpression(stmt: o.Statement): o.Expression|null { if (stmt instanceof o.ExpressionStatement) { return stmt.expr; } else if (stmt instanceof o.ReturnStatement) { diff --git a/packages/compiler/src/config.ts b/packages/compiler/src/config.ts index 4e242000b9..52c4fad95e 100644 --- a/packages/compiler/src/config.ts +++ b/packages/compiler/src/config.ts @@ -13,12 +13,12 @@ import {Identifiers, createIdentifier} from './identifiers'; export class CompilerConfig { - public defaultEncapsulation: ViewEncapsulation; + public defaultEncapsulation: ViewEncapsulation|null; // Whether to support the `