Skip to content

Commit

Permalink
fix(types): Remove unnecessary type assertions (#4821)
Browse files Browse the repository at this point in the history
Now that most of our `isXXX` functions use type predicates, there are a number of places in the code where we no longer have to cast values to a certain type. This covers a few of those instances (pulled from another PR to reduce noise), along with a few others the linter found.
  • Loading branch information
lobsterkatie committed Mar 30, 2022
1 parent 52dafca commit 76b0c1f
Show file tree
Hide file tree
Showing 14 changed files with 21 additions and 22 deletions.
4 changes: 2 additions & 2 deletions packages/browser/src/eventbuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,9 @@ export function eventFromUnknownInput(

return event;
}
if (isError(exception as Error)) {
if (isError(exception)) {
// we have a real Error object, do nothing
return eventFromError(exception as Error);
return eventFromError(exception);
}
if (isPlainObject(exception) || isEvent(exception)) {
// If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize
Expand Down
2 changes: 1 addition & 1 deletion packages/hub/src/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ export class Scope implements ScopeInterface {
} else {
const result = processor({ ...event }, hint) as Event | null;
if (isThenable(result)) {
void (result as PromiseLike<Event | null>)
void result
.then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))
.then(null, reject);
} else {
Expand Down
4 changes: 2 additions & 2 deletions packages/integrations/src/extraerrordata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export class ExtraErrorData implements Integration {
continue;
}
const value = error[key];
extraErrorInfo[key] = isError(value) ? (value as Error).toString() : value;
extraErrorInfo[key] = isError(value) ? value.toString() : value;
}

// Check if someone attached `toJSON` method to grab even more properties (eg. axios is doing that)
Expand All @@ -114,7 +114,7 @@ export class ExtraErrorData implements Integration {

for (const key of Object.keys(serializedError)) {
const value = serializedError[key];
extraErrorInfo[key] = isError(value) ? (value as Error).toString() : value;
extraErrorInfo[key] = isError(value) ? value.toString() : value;
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs/src/utils/instrumentServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ function makeWrappedReqHandler(origReqHandler: ReqHandler): WrappedReqHandler {
// If there is a trace header set, extract the data from it (parentSpanId, traceId, and sampling decision)
let traceparentData;
if (nextReq.headers && isString(nextReq.headers['sentry-trace'])) {
traceparentData = extractTraceparentData(nextReq.headers['sentry-trace'] as string);
traceparentData = extractTraceparentData(nextReq.headers['sentry-trace']);
isDebugBuild() && logger.log(`[Tracing] Continuing trace ${traceparentData?.traceId}.`);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs/src/utils/withSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const withSentry = (origHandler: NextApiHandler): WrappedNextApiHandler =
// If there is a trace header set, extract the data from it (parentSpanId, traceId, and sampling decision)
let traceparentData;
if (req.headers && isString(req.headers['sentry-trace'])) {
traceparentData = extractTraceparentData(req.headers['sentry-trace'] as string);
traceparentData = extractTraceparentData(req.headers['sentry-trace']);
isDebugBuild() && logger.log(`[Tracing] Continuing trace ${traceparentData?.traceId}.`);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/node/src/eventbuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function eventFromUnknownInput(exception: unknown, hint?: EventHint): Eve
const message = `Non-Error exception captured with keys: ${extractExceptionKeysForMessage(exception)}`;

getCurrentHub().configureScope(scope => {
scope.setExtra('__serialized__', normalizeToSize(exception as Record<string, unknown>));
scope.setExtra('__serialized__', normalizeToSize(exception));
});

ex = (hint && hint.syntheticException) || new Error(message);
Expand Down
2 changes: 1 addition & 1 deletion packages/node/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export function tracingHandler(): (
// If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision)
let traceparentData;
if (req.headers && isString(req.headers['sentry-trace'])) {
traceparentData = extractTraceparentData(req.headers['sentry-trace'] as string);
traceparentData = extractTraceparentData(req.headers['sentry-trace']);
}

const transaction = startTransaction(
Expand Down
4 changes: 2 additions & 2 deletions packages/serverless/src/awslambda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export function tryPatchHandler(taskRoot: string, handlerPath: string): void {
}

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
(mod as HandlerModule)[functionName!] = wrapHandler(obj as Handler);
(mod as HandlerModule)[functionName!] = wrapHandler(obj);
}

/**
Expand Down Expand Up @@ -285,7 +285,7 @@ export function wrapHandler<TEvent, TResult>(
let traceparentData;
const eventWithHeaders = event as { headers?: { [key: string]: string } };
if (eventWithHeaders.headers && isString(eventWithHeaders.headers['sentry-trace'])) {
traceparentData = extractTraceparentData(eventWithHeaders.headers['sentry-trace'] as string);
traceparentData = extractTraceparentData(eventWithHeaders.headers['sentry-trace']);
}
const transaction = startTransaction({
name: context.functionName,
Expand Down
2 changes: 1 addition & 1 deletion packages/serverless/src/gcpfunction/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ function _wrapHttpFunction(fn: HttpFunction, wrapOptions: Partial<HttpFunctionWr
let traceparentData;
const reqWithHeaders = req as { headers?: { [key: string]: string } };
if (reqWithHeaders.headers && isString(reqWithHeaders.headers['sentry-trace'])) {
traceparentData = extractTraceparentData(reqWithHeaders.headers['sentry-trace'] as string);
traceparentData = extractTraceparentData(reqWithHeaders.headers['sentry-trace']);
}
const transaction = startTransaction({
name: `${reqMethod} ${reqUrl}`,
Expand Down
4 changes: 2 additions & 2 deletions packages/tracing/src/browser/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ export class MetricsInstrumentation {
}

const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);
const startTime = msToSec(entry.startTime as number);
const startTime = msToSec(entry.startTime);
isDebugBuild() && logger.log('[Measurements] Adding LCP');
this._measurements['lcp'] = { value: metric.value };
this._measurements['mark.lcp'] = { value: timeOrigin + startTime };
Expand All @@ -255,7 +255,7 @@ export class MetricsInstrumentation {
}

const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);
const startTime = msToSec(entry.startTime as number);
const startTime = msToSec(entry.startTime);
isDebugBuild() && logger.log('[Measurements] Adding FID');
this._measurements['fid'] = { value: metric.value };
this._measurements['mark.fid'] = { value: timeOrigin + startTime };
Expand Down
4 changes: 2 additions & 2 deletions packages/tracing/src/hubextensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
SamplingContext,
TransactionContext,
} from '@sentry/types';
import { dynamicRequire, isDebugBuild, isNodeEnv, loadModule, logger } from '@sentry/utils';
import { dynamicRequire, isDebugBuild, isNaN, isNodeEnv, loadModule, logger } from '@sentry/utils';

import { registerErrorInstrumentation } from './errors';
import { IdleTransaction } from './idletransaction';
Expand Down Expand Up @@ -130,7 +130,7 @@ function sample<T extends Transaction>(transaction: T, options: Options, samplin
function isValidSampleRate(rate: unknown): boolean {
// we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (isNaN(rate as any) || !(typeof rate === 'number' || typeof rate === 'boolean')) {
if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {
isDebugBuild() &&
logger.warn(
`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
Expand Down
2 changes: 1 addition & 1 deletion packages/tracing/src/integrations/node/postgres.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export class Postgres implements Integration {
const rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config);

if (isThenable(rv)) {
return (rv as Promise<unknown>).then((res: unknown) => {
return rv.then((res: unknown) => {
span?.finish();
return res;
});
Expand Down
7 changes: 3 additions & 4 deletions packages/utils/src/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,11 +196,10 @@ export function extractExceptionKeysForMessage(exception: any, maxLength: number
*/
export function dropUndefinedKeys<T>(val: T): T {
if (isPlainObject(val)) {
const obj = val as { [key: string]: any };
const rv: { [key: string]: any } = {};
for (const key of Object.keys(obj)) {
if (typeof obj[key] !== 'undefined') {
rv[key] = dropUndefinedKeys(obj[key]);
for (const key of Object.keys(val)) {
if (typeof val[key] !== 'undefined') {
rv[key] = dropUndefinedKeys(val[key]);
}
}
return rv as T;
Expand Down
2 changes: 1 addition & 1 deletion packages/utils/src/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export function isMatchingPattern(value: string, pattern: RegExp | string): bool
}

if (isRegExp(pattern)) {
return (pattern as RegExp).test(value);
return pattern.test(value);
}
if (typeof pattern === 'string') {
return value.indexOf(pattern) !== -1;
Expand Down

0 comments on commit 76b0c1f

Please sign in to comment.