iTranslated by AI
Making Overloaded Method Type Definitions Readonly in TypeScript
Problem and Solution
The reduce method of Array is designed with overloads (though I personally prefer a design where names are distinct, like in Elm, with foldl requiring an initial value and foldl1 not requiring one...).
While you are unlikely to do this by mistake, the way method type definitions are written in es5.d.ts allows them to be overwritten. This is consistent with its actual behavior.
const a = [1, 2, 3];
console.log(a.reduce((acc, val) => acc + val)); // 6
a.reduce = () => 999;
console.log(a.reduce((acc, val) => acc + val)); // 999
class Vector {
constructor(readonly x: number, readonly y: number) {}
distance() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
}
const v = new Vector(3, 4);
console.log(v.distance()); // 5
v.distance = () => 999;
console.log(v.distance()); // 999
However, because this behavior of overwriting methods is confusing, it is better to define them as readonly function properties to prevent overwriting, like this:
class Vector {
constructor(readonly x: number, readonly y: number) {}
readonly distance = () => {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
}
const v = new Vector(3, 4);
console.log(v.distance()); // 5
v.distance = () => 999; // Error: Cannot assign to 'distance' because it is a read-only property.
Furthermore, in the case of overloads, defining them as ordinary properties will result in a duplicate identifier error.
type Reduce<T> = {
readonly reduce: (
callbackfn: (
previousValue: T,
currentValue: T,
currentIndex: number,
array: T[],
) => T,
) => T;
readonly reduce: <U>(
callbackfn: (
previousValue: U,
currentValue: T,
currentIndex: number,
array: T[],
) => U,
initialValue: U,
) => U; // Duplicate identifier 'reduce'.
};
By utilizing the fact that FnA and FnB below are identical:
import type { Equal, Expect } from "npm:@type-challenges/utils";
type FnA = (a: number, b: number) => number;
type FnB = {
(a: number, b: number): number;
};
type cases = [
Expect<Equal<FnA, FnB>>, // No error
];
By defining it this way, you can make the type definition of a method with overloads readonly:
type Reduce<T> = {
readonly reduce: {
(
callbackfn: (
previousValue: T,
currentValue: T,
currentIndex: number,
array: T[],
) => T,
): T;
<U>(
callbackfn: (
previousValue: U,
currentValue: T,
currentIndex: number,
array: T[],
) => U,
initialValue: U,
): U;
};
};
@narumincho/readonly
I am developing a JSR package called @narumincho/readonly, which compiles readonly versions of standard JavaScript types such as ReadonlyArray, ReadonlyMap, and ReadonlySet. I would appreciate it if you could create an Issue or Pull Request if you have any ideas.
References
Discussion