thegreenwebfoundation / co2.js

An npm module for accessing the green web API, and estimating the carbon emissions from using digital services
Other
399 stars 51 forks source link

Typescript types (and JSDocs) do not match behaviour #196

Closed mgriffin-scottlogic closed 5 months ago

mgriffin-scottlogic commented 7 months ago

Describe the bug The CO2 class has an option in code to segment the results when using the default SustainableWebDesign model. However the documentation and types do not reflect this, making it difficult to access cleanly.

To Reproduce Construct the CO2 class like so:

import { co2 } from '@tgwf/co2';
const co2Emission = new co2({
  results: 'segment
});

Make a per byte estimation:

const bytesSent = 1000 * 1000 * 1000;
const greenHost = false;

const estimatedCO2 = co2Emission.perByte(bytesSent, greenHost);

Unable to access the individual components of the result:

console.log(result.co2.networkCO2); // Gives error: Property 'networkCO2' does not exist on type 'number'.

Expected behavior A type/typedef along the lines of:

interface CO2EstimateComponents {
  consumerDeviceCO2: number;
  networkCO2: number;
  dataCenterCO2: number;
  productionCO2: number;
  total: number;
}

Is defined and the return types are changed to be a union of number and this type.

Environment (please complete the following information):

Additional context (if applicable) Not sure if this is intentional and the ability to segment results should not be exposed?

I would like to use this mode to extract the network CO2 emissions separately from the total. I have a fork with changes to the JSDoc types, I assume to change the Typescript definitions I would need to make a pull request to the DefinitelyTyped repo?

sfishel18 commented 6 months ago

yes i think you would need to make a pull request to DefinitelyTyped to fix it. and in the meantime you could do something like this locally:

interface CO2EstimateComponents {
  consumerDeviceCO2: number;
  networkCO2: number;
  dataCenterCO2: number;
  productionCO2: number;
  total: number;
}

const co2Emission = new co2({
  results: "segment",
});

const bytesSent = 1000 * 1000 * 1000;
const greenHost = false;

const estimatedCO2 = co2Emission.perByte(bytesSent, greenHost) as unknown as CO2EstimateComponents;
console.log(estimatedCO2.networkCO2);
fershad commented 6 months ago

@mgriffin-scottlogic thanks, please do submit a PR to update the JSDoc comments. To update the types, please do update the DefinitelyTyped project definitions.

fershad commented 5 months ago

Closing this as the updates have been merged into the DefinitelyTyped project.