segmentio / analytics-next

Segment Analytics.js 2.0
https://segment.com/docs/connections/sources/catalog/libraries/website/javascript
MIT License
384 stars 128 forks source link

analytics.user function should be listed as optionally undefined in typescript definitions #1097

Open william-will-angi opened 1 week ago

william-will-angi commented 1 week ago

We are running into an issue for users that have ad blocking or cross-site tracking disabled.

Our code:

import type { AnalyticsSnippet } from '@segment/analytics-next';

const getAnalytics = (): AnalyticsSnippet | undefined => typeof window !== 'undefined' ? window.analytics : undefined;

getAnalytics()?.user()

Throws the error:

VM70:1 Uncaught TypeError: analytics.user is not a function
    at <anonymous>:1:11

My expectation is that the typescript definition lists the user function as optionally undefined so that typescript enforces that we call the code as:

getAnalytics()?.user?.()

This would prevent us from running into runtime errors for users with ad blockers or cross site trackers disabled.

We are using @segment/analytics-next@1.70.0 & typescript@5.5.2