Skip to content

cpuTemp ​

cpuTemp returns the highest reported sensor temperature, an approximation of the CPU package temperature, since sensors are not labeled consistently as "CPU" across platforms.

SignaturecpuTemp(unit?: "celsius" | "fahrenheit"): f32?
tyrus
import { cpuTemp } from "tyrus:os";

const celsius: f32? = cpuTemp();
if (celsius) {
    print(`${celsius}°C`);
}

const fahrenheit: f32? = cpuTemp("fahrenheit");
if (fahrenheit) {
    print(`${fahrenheit}°F`);
}

unit defaults to "celsius" when omitted. Passing any value other than "celsius" or "fahrenheit" is a compile-time type error.

Absence is a valid outcome

Returns absent, not an aborted program, when no thermal sensor is available, common in VMs, containers, and on platforms without a sensor backend.

A value from outside must be narrowed first

unit only accepts the literals "celsius" and "fahrenheit", a plain string read from a config file, an environment variable, or an HTTP response does not satisfy that type and fails to compile if passed directly. Branch on the external value and call cpuTemp with a literal in each branch instead:

tyrus
import { cpuTemp } from "tyrus:os";

// Stands in for a config file, an HTTP response, a CLI argument, any
// value only known once the program is running.
const readPreferredUnit = (): string => {
  return "fahrenheit";
};

const main = (): void => {
  const preferredUnit: string = readPreferredUnit();

  // `preferredUnit` is a plain `string`, not the literal union `cpuTemp`
  // expects, so it cannot be passed through directly, narrow it to one
  // of the two accepted literals first.
  let temp: f32?;
  if (preferredUnit === "fahrenheit") {
    temp = cpuTemp("fahrenheit");
  } else {
    temp = cpuTemp("celsius");
  }
  if (temp) {
    print(temp);
  }
};

Anything that is not "fahrenheit" falls into the else branch above and is treated as Celsius; reject it explicitly there instead if silently defaulting is not what you want.