LoginSignup
3
0

【TypeScript】The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

Last updated at Posted at 2023-08-01
const dates = [
  "2024-11-12T00:00:00.000Z",
  "2024-02-12T00:00:00.000Z",
  "2025-08-26T00:00:00.000Z",
  "2020-11-16T00:00:00.000Z",
  "2020-11-14T00:00:00.000Z",
];

const sortedDates = dates.sort((a, b) => {
  return new Date(a) - new Date(b);
});

上記のように、配列に日付を格納して日付の古い順にソートするようなプログラムを書くと、以下のようなコンパイルエラーが出力されます。

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

これは、TypeScriptにおいて、演算子(算術演算子、比較演算子など)を使用する際に、演算子の左辺が予期しない型である場合に発生します。

今回の場合、-の左辺がDate型であることが原因となっています。TypeScriptはDateの比較をサポートしていないので、別の型にして比較する必要があります。

Dateが持つメソッドgetTime()またはvalueOf()を使用することで、このエラーは回避することができます。

getTime()
const dates = [
  "2024-11-12T00:00:00.000Z",
  "2024-02-12T00:00:00.000Z",
  "2025-08-26T00:00:00.000Z",
  "2020-11-16T00:00:00.000Z",
  "2020-11-14T00:00:00.000Z",
];

const sortedDates = dates.sort((a, b) => {
  return new Date(a).getTime() - new Date(b).getTime();
});
valueOf()
const dates = [
  "2024-11-12T00:00:00.000Z",
  "2024-02-12T00:00:00.000Z",
  "2025-08-26T00:00:00.000Z",
  "2020-11-16T00:00:00.000Z",
  "2020-11-14T00:00:00.000Z",
];

const sortedDates = dates.sort((a, b) => {
  return new Date(a).valueOf() - new Date(b).valueOf();
});
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0