Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: utilize type narrowing #33075

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -15,7 +15,7 @@ export class HeroDetailService {
// Returns a clone which caller may modify safely
getHero(id: number | string): Observable<Hero> {
if (typeof id === 'string') {
id = parseInt(id as string, 10);
id = parseInt(id, 10);
}
return this.heroService.getHero(id).pipe(
map(hero => {
Expand Down
14 changes: 7 additions & 7 deletions aio/content/examples/testing/src/app/model/hero.service.ts
Expand Up @@ -18,7 +18,7 @@ export class HeroService {
constructor(private http: HttpClient) { }

/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(heroes => this.log(`fetched heroes`)),
Expand All @@ -29,7 +29,7 @@ export class HeroService {
/** GET hero by id. Return `undefined` when id not found */
getHero<Data>(id: number | string): Observable<Hero> {
if (typeof id === 'string') {
id = parseInt(id as string, 10);
id = parseInt(id, 10);
}
const url = `${this.heroesUrl}/?id=${id}`;
return this.http.get<Hero[]>(url)
Expand All @@ -46,14 +46,14 @@ export class HeroService {
//////// Save methods //////////

/** POST: add a new hero to the server */
addHero (hero: Hero): Observable<Hero> {
addHero(hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
tap((hero: Hero) => this.log(`added hero w/ id=${hero.id}`)),
tap((addedHero) => this.log(`added hero w/ id=${addedHero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
}
/** DELETE: delete the hero from the server */
deleteHero (hero: Hero | number): Observable<Hero> {
deleteHero(hero: Hero | number): Observable<Hero> {
const id = typeof hero === 'number' ? hero : hero.id;
const url = `${this.heroesUrl}/${id}`;

Expand All @@ -64,7 +64,7 @@ export class HeroService {
}

/** PUT: update the hero on the server */
updateHero (hero: Hero): Observable<any> {
updateHero(hero: Hero): Observable<any> {
return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
tap(_ => this.log(`updated hero id=${hero.id}`)),
catchError(this.handleError<any>('updateHero'))
Expand All @@ -75,7 +75,7 @@ export class HeroService {
* This error handler lets the app continue to run as if no error occurred.
* @param operation - name of the operation that failed
*/
private handleError<T> (operation = 'operation') {
private handleError<T>(operation = 'operation') {
return (error: HttpErrorResponse): Observable<T> => {

// TODO: send the error to remote logging infrastructure
Expand Down
Expand Up @@ -42,9 +42,9 @@ export class TestHeroService extends HeroService {

getHero(id: number | string): Observable<Hero> {
if (typeof id === 'string') {
id = parseInt(id as string, 10);
id = parseInt(id, 10);
}
let hero = this.heroes.find(h => h.id === id);
const hero = this.heroes.find(h => h.id === id);
return this.lastResult = asyncData(hero);
}

Expand Down
10 changes: 5 additions & 5 deletions packages/animations/browser/src/dsl/animation_ast_builder.ts
Expand Up @@ -244,12 +244,12 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor {
(metadata.styles as(ɵStyleData | string)[]).forEach(styleTuple => {
if (typeof styleTuple == 'string') {
if (styleTuple == AUTO_STYLE) {
styles.push(styleTuple as string);
styles.push(styleTuple);
} else {
context.errors.push(`The provided style string value ${styleTuple} is not allowed.`);
}
} else {
styles.push(styleTuple as ɵStyleData);
styles.push(styleTuple);
}
});
} else {
Expand Down Expand Up @@ -518,7 +518,7 @@ function consumeOffset(styles: ɵStyleData | string | (ɵStyleData | string)[]):
}
});
} else if (isObject(styles) && styles.hasOwnProperty('offset')) {
const obj = styles as ɵStyleData;
const obj = styles;
offset = parseFloat(obj['offset'] as string);
delete obj['offset'];
}
Expand All @@ -534,8 +534,8 @@ function constructTimingAst(value: string | number | AnimateTimings, errors: any
if (value.hasOwnProperty('duration')) {
timings = value as AnimateTimings;
} else if (typeof value == 'number') {
const duration = resolveTiming(value as number, errors).duration;
return makeTimingAst(duration as number, 0, '');
const duration = resolveTiming(value, errors).duration;
return makeTimingAst(duration, 0, '');
}

const strValue = value as string;
Expand Down
Expand Up @@ -13,9 +13,8 @@ export function parseTransitionExpr(
transitionValue: string | TransitionMatcherFn, errors: string[]): TransitionMatcherFn[] {
const expressions: TransitionMatcherFn[] = [];
if (typeof transitionValue == 'string') {
(<string>transitionValue)
.split(/\s*,\s*/)
.forEach(str => parseInnerTransitionStr(str, expressions, errors));
transitionValue.split(/\s*,\s*/).forEach(
str => parseInnerTransitionStr(str, expressions, errors));
} else {
expressions.push(<TransitionMatcherFn>transitionValue);
}
Expand All @@ -30,7 +29,7 @@ function parseInnerTransitionStr(
expressions.push(result);
return;
}
eventStr = result as string;
eventStr = result;
}

const match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);
Expand Down
Expand Up @@ -1708,7 +1708,7 @@ function _flattenGroupPlayersRecur(players: AnimationPlayer[], finalPlayers: Ani
if (player instanceof AnimationGroupPlayer) {
_flattenGroupPlayersRecur(player.players, finalPlayers);
} else {
finalPlayers.push(player as AnimationPlayer);
finalPlayers.push(player);
}
}
}
Expand Down
8 changes: 3 additions & 5 deletions packages/animations/browser/src/util.ts
Expand Up @@ -26,7 +26,7 @@ export const NG_ANIMATING_SELECTOR = '.ng-animating';
export function resolveTimingValue(value: string | number) {
if (typeof value == 'number') return value;

const matches = (value as string).match(/^(-?[\.\d]+)(m?s)/);
const matches = value.match(/^(-?[\.\d]+)(m?s)/);
if (!matches || matches.length < 2) return 0;

return _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
Expand Down Expand Up @@ -73,7 +73,7 @@ function parseTimeExpression(
easing = easingVal;
}
} else {
duration = <number>exp;
duration = exp;
}

if (!allowNegativeValues) {
Expand Down Expand Up @@ -214,10 +214,8 @@ const PARAM_REGEX =
export function extractStyleParams(value: string | number): string[] {
let params: string[] = [];
if (typeof value === 'string') {
const val = value.toString();

let match: any;
while (match = PARAM_REGEX.exec(val)) {
while (match = PARAM_REGEX.exec(value)) {
params.push(match[1] as string);
}
PARAM_REGEX.lastIndex = 0;
Expand Down
6 changes: 3 additions & 3 deletions packages/common/http/src/client.ts
Expand Up @@ -457,7 +457,7 @@ export class HttpClient {
if (first instanceof HttpRequest) {
// It is. The other arguments must be undefined (per the signatures) and can be
// ignored.
req = first as HttpRequest<any>;
req = first;
} else {
// It's a string, so it represents a URL. Construct a request based on it,
// and incorporate the remaining arguments (assuming `GET` unless a method is
Expand All @@ -477,7 +477,7 @@ export class HttpClient {
if (options.params instanceof HttpParams) {
params = options.params;
} else {
params = new HttpParams({ fromObject: options.params } as HttpParamsOptions);
params = new HttpParams({fromObject: options.params});
}
}

Expand Down Expand Up @@ -1798,7 +1798,7 @@ export class HttpClient {
}): Observable<Blob>;

/**
* Constructs a `PATCH` request that interprets the body as as a text string and
* Constructs a `PATCH` request that interprets the body as a text string and
* returns the response as a string value.
*
* @param url The endpoint URL.
Expand Down
4 changes: 2 additions & 2 deletions packages/common/src/i18n/localization.ts
Expand Up @@ -94,9 +94,9 @@ export class NgLocaleLocalization extends NgLocalization {
export function getPluralCase(locale: string, nLike: number | string): Plural {
// TODO(vicb): lazy compute
if (typeof nLike === 'string') {
nLike = parseInt(<string>nLike, 10);
nLike = parseInt(nLike, 10);
}
const n: number = nLike as number;
const n: number = nLike;
const nDecimal = n.toString().replace(/^[^.]*\.?/, '');
const i = Math.floor(Math.abs(n));
const v = nDecimal.length;
Expand Down
2 changes: 1 addition & 1 deletion packages/common/src/pipes/deprecated/number_pipe.ts
Expand Up @@ -50,7 +50,7 @@ function formatNumber(
}
}

return NumberFormatter.format(value as number, locale, style, {
return NumberFormatter.format(value, locale, style, {
minimumIntegerDigits: minInt,
minimumFractionDigits: minFraction,
maximumFractionDigits: maxFraction,
Expand Down
Expand Up @@ -624,7 +624,7 @@ function findClassSymbolInContext(type: StaticSymbol, context: TypeContext): ts.
// This handles a case where an <packageName>/index.d.ts and a <packageName>/<packageName>.d.ts
// are in the same directory. If we are looking for <packageName>/<packageName> and didn't
// find it, look for <packageName>/index.d.ts as the program might have found that instead.
const p = type.filePath as string;
const p = type.filePath;
const m = p.match(INDEX_PATTERN);
if (m) {
const indexVersion = path.join(path.dirname(p), 'index.d.ts');
Expand Down
4 changes: 2 additions & 2 deletions packages/compiler-cli/src/metadata/evaluator.ts
Expand Up @@ -306,7 +306,7 @@ export class Evaluator {
error = propertyValue;
return true; // Stop the forEachChild.
} else {
obj[<string>propertyName] = isPropertyAssignment(assignment) ?
obj[propertyName] = isPropertyAssignment(assignment) ?
recordEntry(propertyValue, assignment.initializer) :
propertyValue;
}
Expand Down Expand Up @@ -401,7 +401,7 @@ export class Evaluator {
return recordEntry(member, node);
}
if (expression && this.isFoldable(propertyAccessExpression.expression))
return (<any>expression)[<string>member];
return (<any>expression)[member];
if (isMetadataModuleReferenceExpression(expression)) {
// A select into a module reference and be converted into a reference to the symbol
// in the module
Expand Down
Expand Up @@ -271,7 +271,7 @@ export function extractQueryMetadata(
} else if (typeof arg === 'string') {
predicate = [arg];
} else if (isStringArrayOrDie(arg, '@' + name)) {
predicate = arg as string[];
predicate = arg;
} else {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE, node, `@${name} predicate cannot be interpreted`);
Expand Down
25 changes: 13 additions & 12 deletions packages/compiler/src/metadata_resolver.ts
Expand Up @@ -1012,18 +1012,19 @@ export class CompileMetadataResolver {
return;
} else {
const providersInfo =
(<string[]>providers.reduce(
(soFar: string[], seenProvider: any, seenProviderIdx: number) => {
if (seenProviderIdx < providerIdx) {
soFar.push(`${stringifyType(seenProvider)}`);
} else if (seenProviderIdx == providerIdx) {
soFar.push(`?${stringifyType(seenProvider)}?`);
} else if (seenProviderIdx == providerIdx + 1) {
soFar.push('...');
}
return soFar;
},
[]))
providers
.reduce(
(soFar: string[], seenProvider: any, seenProviderIdx: number) => {
if (seenProviderIdx < providerIdx) {
soFar.push(`${stringifyType(seenProvider)}`);
} else if (seenProviderIdx == providerIdx) {
soFar.push(`?${stringifyType(seenProvider)}?`);
} else if (seenProviderIdx == providerIdx + 1) {
soFar.push('...');
}
return soFar;
},
[])
.join(', ');
this._reportError(
syntaxError(
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/render3/node_selector_matcher.ts
Expand Up @@ -81,7 +81,7 @@ export function isNodeMatchingSelector(
const current = selector[i];
if (typeof current === 'number') {
// If we finish processing a :not selector and it hasn't failed, return false
if (!skipToNextSelector && !isPositive(mode) && !isPositive(current as number)) {
if (!skipToNextSelector && !isPositive(mode) && !isPositive(current)) {
return false;
}
// If we are skipping to the next :not() and this mode flag is positive,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/render3/query.ts
Expand Up @@ -195,7 +195,7 @@ class TQuery_ implements TQuery {

private matchTNode(tView: TView, tNode: TNode): void {
if (Array.isArray(this.metadata.predicate)) {
const localNames = this.metadata.predicate as string[];
const localNames = this.metadata.predicate;
for (let i = 0; i < localNames.length; i++) {
this.matchTNodeWithReadOption(tView, tNode, getIdxOfMatchingSelector(tNode, localNames[i]));
}
Expand Down
5 changes: 2 additions & 3 deletions packages/core/src/render3/util/attrs_utils.ts
Expand Up @@ -73,9 +73,8 @@ export function setUpAttributes(renderer: Renderer3, native: RElement, attrs: TA
}
} else {
isProc ?
(renderer as ProceduralRenderer3)
.setAttribute(native, attrName as string, attrVal as string) :
native.setAttribute(attrName as string, attrVal as string);
(renderer as ProceduralRenderer3).setAttribute(native, attrName, attrVal as string) :
native.setAttribute(attrName, attrVal as string);
}
i++;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/render3/util/styling_utils.ts
Expand Up @@ -397,7 +397,7 @@ export function normalizeIntoStylingMap(

if (props) {
for (let i = 0; i < props.length; i++) {
const prop = props[i] as string;
const prop = props[i];
const newProp = normalizeProps ? hyphenate(prop) : prop;
const value = allValuesTrue ? true : map ![prop];
addItemToStylingMap(stylingMapArr, newProp, value, true);
Expand Down
8 changes: 3 additions & 5 deletions packages/core/src/sanitization/bypass.ts
Expand Up @@ -88,9 +88,8 @@ class SafeResourceUrlImpl extends SafeValueImpl implements SafeResourceUrl {
}

export function unwrapSafeValue(value: string | SafeValue): string {
return value instanceof SafeValueImpl ?
(value as SafeValueImpl).changingThisBreaksApplicationSecurity :
(value as string);
return value instanceof SafeValueImpl ? value.changingThisBreaksApplicationSecurity :
value as string;
}


Expand All @@ -116,8 +115,7 @@ export function allowSanitizationBypassAndThrow(value: any, type: BypassType): b
}

export function getSanitizationBypassType(value: any): BypassType|null {
return value instanceof SafeValueImpl && (value as SafeValueImpl).getTypeName() as BypassType ||
null;
return value instanceof SafeValueImpl && value.getTypeName() as BypassType || null;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/core/testing/src/async_fallback.ts
Expand Up @@ -45,7 +45,7 @@ export function asyncFallback(fn: Function): (done: any) => any {
}
runInTestZone(fn, this, done, (err: any) => {
if (typeof err === 'string') {
return done.fail(new Error(<string>err));
return done.fail(new Error(err));
} else {
done.fail(err);
}
Expand Down
6 changes: 3 additions & 3 deletions packages/forms/src/model.ts
Expand Up @@ -48,11 +48,11 @@ function _find(control: AbstractControl, path: Array<string|number>| string, del
if (path == null) return null;

if (!(path instanceof Array)) {
path = (<string>path).split(delimiter);
path = path.split(delimiter);
}
if (path instanceof Array && (path.length === 0)) return null;
if (path instanceof Array && path.length === 0) return null;

return (<Array<string|number>>path).reduce((v: AbstractControl | null, name) => {
return path.reduce((v: AbstractControl | null, name) => {
if (v instanceof FormGroup) {
return v.controls.hasOwnProperty(name as string) ? v.controls[name] : null;
}
Expand Down