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

Open
#1,097 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
45/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
typescript
Domain
api

Research direction

Start by locating the TypeScript definition for AnalyticsSnippet and its user member in the analytics-next package. Check the existing type tests or validation commands, if present; done means the definition reflects that user may be absent and the shown optional call type-checks without permitting the unsafe call.

Written by the indexing model from the issue text.

Description

enhancement

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

Dominant language
TypeScript
Stars
477
Forks
160
Avg merge
6h 19m
Merged PRs (30d)
4

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from segmentio/analytics-next

All issues in segmentio/analytics-next

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.