web-vitals icon indicating copy to clipboard operation
web-vitals copied to clipboard

Fix Types of Attribution

Open narui1125 opened this issue 3 years ago • 1 comments

Hello, There may be a problem with types of attributtion.

As an example, a type error occurs in the following code in call onCLS.

import { CLSMetricWithAttribution, MetricWithAttribution, onCLS } from 'web-vitals/attribution';

const sendCLSMetrics = (metric: CLSMetricWithAttribution) => {
    console.log(metric.attribution)
}

onCLS(sendCLSMetrics); // type error

const sendMetrics = (metric: MetricWithAttribution) => {
    console.log(metric.attribution)
}

onCLS(sendMetrics); // type error

I think there is a problem with extending callback function. Sorry if there is any problem with my usage.

narui1125 avatar Sep 24 '22 04:09 narui1125

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

google-cla[bot] avatar Sep 24 '22 04:09 google-cla[bot]

As per the README you should be importing it like this:

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

const sendCLSMetrics = (attribution) => {
    console.log(attribution)
}
``

tunetheweb avatar Apr 04 '23 11:04 tunetheweb

Thank you for your response.

It seems that the code you provided will work, but there might be an problem when adding the type.(I would like to add type annotations for code completion)

'onCLS' accepts 'CLSReportCallbackWithAttribution', but 'CLSReportCallbackWithAttribution' can also accept not only 'CLSMetricWithAttribution' but also 'CLSMetric' and 'Metric' types, so the 'attribution' property is not guaranteed to exist on the type.

It seems like the following approach would work, but I think 'CLSReportCallbackWithAttribution' should only accept 'CLSMetricWithAttribution'.

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

const sendCLSMetrics: CLSReportCallbackWithAttribution = (param) => {
  if (!('attribution' in param)) {
    return
  }

  console.log(param.attribution)
}

onCLS(sendCLSMetrics);
スクリーンショット 2023-04-09 15 41 52

narui1125 avatar Apr 09 '23 07:04 narui1125

I believe this has been fixed in latest main.

tunetheweb avatar Jul 07 '23 12:07 tunetheweb