web-vitals: attribution typescript error

Using the example from the README.md

import {onCLS, onFID, onLCP} from 'web-vitals/attribution';

function sendToGoogleAnalytics({name, delta, value, id, attribution}) {
  const eventParams = {
    // Built-in params:
    value: delta, // Use `delta` so the value can be summed.
    // Custom params:
    metric_id: id, // Needed to aggregate events.
    metric_value: value, // Optional.
    metric_delta: delta, // Optional.
  };

  switch (name) {
    case 'CLS':
      eventParams.debug_target = attribution.largestShiftTarget;
      break;
    case 'FID':
      eventParams.debug_target = attribution.eventTarget;
      break;
    case 'LCP':
      eventParams.debug_target = attribution.element;
      break;
  }

  // Assumes the global `gtag()` function exists, see:
  // https://developers.google.com/analytics/devguides/collection/ga4
  gtag('event', name, eventParams);
}

onCLS(sendToGoogleAnalytics);
onFID(sendToGoogleAnalytics);
onLCP(sendToGoogleAnalytics);

Generates a typescript error:

Argument of type '({ name, delta, value, id, attribution }: { name: any; delta: any; value: any; id: any; attribution: any; }) => void' is not assignable to parameter of type 'CLSReportCallbackWithAttribution'.
  Types of parameters '__0' and 'metric' are incompatible.
    Property 'attribution' is missing in type 'CLSMetric' but required in type '{ name: any; delta: any; value: any; id: any; attribution: any; }'.

It seems the function still thinks it’s a CLSMetric and not a CLSMetricWithAttribution

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 16 (7 by maintainers)

Most upvoted comments

It looks like src/attribution/onCLS.ts specifically had an incorrect type which fixes the onCLS((x) => { x.attribution; }); issue.

But a bigger fix was also needed for all the metrics for a onCLS(callAFunction) call.