GoogleChrome / web-vitals

Essential metrics for a healthy site.
https://web.dev/vitals
Apache License 2.0
7.49k stars 410 forks source link

Type 'XXXMetricWithAttribution' is not assignable to type 'MetricWithAttribution' #408

Closed mcanu closed 4 months ago

mcanu commented 9 months ago

When trying to be more generic and use MetricWithAttribution with FIDMetricWithAttribution (or other XXXMetricWithAttribution) I get this Typescript error:

Type 'FIDMetricWithAttribution' is not assignable to type 'MetricWithAttribution'.
  Types of property 'attribution' are incompatible.
    Type 'FIDAttribution' is not assignable to type '{ [key: string]: unknown; }'.
      Index signature for type 'string' is missing in type 'FIDAttribution'.

How to reproduce:

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

const fidMetric: FIDMetricWithAttribution = {...};
const metricWithAttribution: MetricWithAttribution = fidMetric;

I fixed this by creating a "new" MetricWithAttribution with the correct types:

import {
  CLSAttribution,
  FCPAttribution,
  FIDAttribution,
  FIDMetricWithAttribution,
  INPAttribution,
  LCPAttribution,
  Metric,
  TTFBAttribution,
} from 'web-vitals/attribution';

interface MetricWithAttribution extends Metric {
  attribution:
    | FIDAttribution
    | CLSAttribution
    | LCPAttribution
    | TTFBAttribution
    | INPAttribution
    | FCPAttribution;
}

const fidMetric: FIDMetricWithAttribution = {};
const metricWithAttribution: MetricWithAttribution = fidMetric;

The existing MetricWithAttribution definition should be updated or fixed to accommodate these use cases.

tunetheweb commented 4 months ago

Resolved with #471. Will be included in v4 as breaking change to the types.