Anders Hejlsberg (ahejlsberg) · GitHub

function f3<T extends { [key: string]: any }>(obj: T) {
    let foo = obj['foo'];
    let bar = obj['bar'];
    obj['foo'] = 123;  // Error  - (its writable and matches the parameters why error?)
    obj['bar'] = 'x';  // Error - (ditto)
}
function f5<T extends Readonly<{ [key: string]: any }>>(obj: T) {
    let foo = obj['foo'];
    let bar = obj['bar'];
    obj['foo'] = 123;  // Error
    obj['bar'] = 'x';  // Error
}
declare const obj: {
  foo: boolean;
  bar: boolean;
};
f5(obj);

Shouldn't TypeScript assume the user is reading the function parameters and trust them not to call f3 because of the any type and the fact that it is non-readonly?

Conversely, the user may have a special need for writing a writable any typed function like f3, and now they are not allowed to write it. That could be frustrating.

Read the original on github.com ↗