Skip to content

Commit 76b0c1f

Browse files
authored
fix(types): Remove unnecessary type assertions (#4821)
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.
1 parent 52dafca commit 76b0c1f

File tree

14 files changed

+21
-22
lines changed

14 files changed

+21
-22
lines changed

packages/browser/src/eventbuilder.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,9 +228,9 @@ export function eventFromUnknownInput(
228228

229229
return event;
230230
}
231-
if (isError(exception as Error)) {
231+
if (isError(exception)) {
232232
// we have a real Error object, do nothing
233-
return eventFromError(exception as Error);
233+
return eventFromError(exception);
234234
}
235235
if (isPlainObject(exception) || isEvent(exception)) {
236236
// If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize

packages/hub/src/scope.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,7 @@ export class Scope implements ScopeInterface {
466466
} else {
467467
const result = processor({ ...event }, hint) as Event | null;
468468
if (isThenable(result)) {
469-
void (result as PromiseLike<Event | null>)
469+
void result
470470
.then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))
471471
.then(null, reject);
472472
} else {

packages/integrations/src/extraerrordata.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ export class ExtraErrorData implements Integration {
105105
continue;
106106
}
107107
const value = error[key];
108-
extraErrorInfo[key] = isError(value) ? (value as Error).toString() : value;
108+
extraErrorInfo[key] = isError(value) ? value.toString() : value;
109109
}
110110

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

115115
for (const key of Object.keys(serializedError)) {
116116
const value = serializedError[key];
117-
extraErrorInfo[key] = isError(value) ? (value as Error).toString() : value;
117+
extraErrorInfo[key] = isError(value) ? value.toString() : value;
118118
}
119119
}
120120

packages/nextjs/src/utils/instrumentServer.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ function makeWrappedReqHandler(origReqHandler: ReqHandler): WrappedReqHandler {
246246
// If there is a trace header set, extract the data from it (parentSpanId, traceId, and sampling decision)
247247
let traceparentData;
248248
if (nextReq.headers && isString(nextReq.headers['sentry-trace'])) {
249-
traceparentData = extractTraceparentData(nextReq.headers['sentry-trace'] as string);
249+
traceparentData = extractTraceparentData(nextReq.headers['sentry-trace']);
250250
isDebugBuild() && logger.log(`[Tracing] Continuing trace ${traceparentData?.traceId}.`);
251251
}
252252

packages/nextjs/src/utils/withSentry.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ export const withSentry = (origHandler: NextApiHandler): WrappedNextApiHandler =
4949
// If there is a trace header set, extract the data from it (parentSpanId, traceId, and sampling decision)
5050
let traceparentData;
5151
if (req.headers && isString(req.headers['sentry-trace'])) {
52-
traceparentData = extractTraceparentData(req.headers['sentry-trace'] as string);
52+
traceparentData = extractTraceparentData(req.headers['sentry-trace']);
5353
isDebugBuild() && logger.log(`[Tracing] Continuing trace ${traceparentData?.traceId}.`);
5454
}
5555

packages/node/src/eventbuilder.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ export function eventFromUnknownInput(exception: unknown, hint?: EventHint): Eve
5757
const message = `Non-Error exception captured with keys: ${extractExceptionKeysForMessage(exception)}`;
5858

5959
getCurrentHub().configureScope(scope => {
60-
scope.setExtra('__serialized__', normalizeToSize(exception as Record<string, unknown>));
60+
scope.setExtra('__serialized__', normalizeToSize(exception));
6161
});
6262

6363
ex = (hint && hint.syntheticException) || new Error(message);

packages/node/src/handlers.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ export function tracingHandler(): (
6363
// If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision)
6464
let traceparentData;
6565
if (req.headers && isString(req.headers['sentry-trace'])) {
66-
traceparentData = extractTraceparentData(req.headers['sentry-trace'] as string);
66+
traceparentData = extractTraceparentData(req.headers['sentry-trace']);
6767
}
6868

6969
const transaction = startTransaction(

packages/serverless/src/awslambda.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ export function tryPatchHandler(taskRoot: string, handlerPath: string): void {
156156
}
157157

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

162162
/**
@@ -285,7 +285,7 @@ export function wrapHandler<TEvent, TResult>(
285285
let traceparentData;
286286
const eventWithHeaders = event as { headers?: { [key: string]: string } };
287287
if (eventWithHeaders.headers && isString(eventWithHeaders.headers['sentry-trace'])) {
288-
traceparentData = extractTraceparentData(eventWithHeaders.headers['sentry-trace'] as string);
288+
traceparentData = extractTraceparentData(eventWithHeaders.headers['sentry-trace']);
289289
}
290290
const transaction = startTransaction({
291291
name: context.functionName,

packages/serverless/src/gcpfunction/http.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ function _wrapHttpFunction(fn: HttpFunction, wrapOptions: Partial<HttpFunctionWr
5353
let traceparentData;
5454
const reqWithHeaders = req as { headers?: { [key: string]: string } };
5555
if (reqWithHeaders.headers && isString(reqWithHeaders.headers['sentry-trace'])) {
56-
traceparentData = extractTraceparentData(reqWithHeaders.headers['sentry-trace'] as string);
56+
traceparentData = extractTraceparentData(reqWithHeaders.headers['sentry-trace']);
5757
}
5858
const transaction = startTransaction({
5959
name: `${reqMethod} ${reqUrl}`,

packages/tracing/src/browser/metrics.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ export class MetricsInstrumentation {
238238
}
239239

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

257257
const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);
258-
const startTime = msToSec(entry.startTime as number);
258+
const startTime = msToSec(entry.startTime);
259259
isDebugBuild() && logger.log('[Measurements] Adding FID');
260260
this._measurements['fid'] = { value: metric.value };
261261
this._measurements['mark.fid'] = { value: timeOrigin + startTime };

packages/tracing/src/hubextensions.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
SamplingContext,
88
TransactionContext,
99
} from '@sentry/types';
10-
import { dynamicRequire, isDebugBuild, isNodeEnv, loadModule, logger } from '@sentry/utils';
10+
import { dynamicRequire, isDebugBuild, isNaN, isNodeEnv, loadModule, logger } from '@sentry/utils';
1111

1212
import { registerErrorInstrumentation } from './errors';
1313
import { IdleTransaction } from './idletransaction';
@@ -130,7 +130,7 @@ function sample<T extends Transaction>(transaction: T, options: Options, samplin
130130
function isValidSampleRate(rate: unknown): boolean {
131131
// we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck
132132
// eslint-disable-next-line @typescript-eslint/no-explicit-any
133-
if (isNaN(rate as any) || !(typeof rate === 'number' || typeof rate === 'boolean')) {
133+
if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {
134134
isDebugBuild() &&
135135
logger.warn(
136136
`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(

packages/tracing/src/integrations/node/postgres.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ export class Postgres implements Integration {
8181
const rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config);
8282

8383
if (isThenable(rv)) {
84-
return (rv as Promise<unknown>).then((res: unknown) => {
84+
return rv.then((res: unknown) => {
8585
span?.finish();
8686
return res;
8787
});

packages/utils/src/object.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -196,11 +196,10 @@ export function extractExceptionKeysForMessage(exception: any, maxLength: number
196196
*/
197197
export function dropUndefinedKeys<T>(val: T): T {
198198
if (isPlainObject(val)) {
199-
const obj = val as { [key: string]: any };
200199
const rv: { [key: string]: any } = {};
201-
for (const key of Object.keys(obj)) {
202-
if (typeof obj[key] !== 'undefined') {
203-
rv[key] = dropUndefinedKeys(obj[key]);
200+
for (const key of Object.keys(val)) {
201+
if (typeof val[key] !== 'undefined') {
202+
rv[key] = dropUndefinedKeys(val[key]);
204203
}
205204
}
206205
return rv as T;

packages/utils/src/string.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ export function isMatchingPattern(value: string, pattern: RegExp | string): bool
9494
}
9595

9696
if (isRegExp(pattern)) {
97-
return (pattern as RegExp).test(value);
97+
return pattern.test(value);
9898
}
9999
if (typeof pattern === 'string') {
100100
return value.indexOf(pattern) !== -1;

0 commit comments

Comments
 (0)