ZuBB ZuBB - 6 months ago 68
TypeScript Question

Type checking for 2nd param of String.replace() method is not consistent?

Below there is pretty simple example in TypeScript. Could you please explain why 2nd expression in "tests" section is valid (others are not, as it is expected) accordingly to TS playground?

let p = '{pattern}';
let a = 'bar ' + p + ' foo';
let h: { key: string } = { key: a};
let k = 'key';
let n = 0;

// tests
a.replace(p, n);
h[k].replace(p, n);
h.key.replace(p, n);
h['key'].replace(p, n);

My best guess is that it somehow related to hash/or work related with it, but I lack some knowledge..


The 2nd test:

h[k].replace(p, n);

Is fine with the compiler because h[k] is of type any, because you are accessing the property using an index.
If you want that to fail in compilation you need to do:

let h: { [key: string]: string } = { key: a };
h[k].replace(p, n); // Error: Argument of type 'string' is not assignable to parameter of type 'RegExp'

(code in playground`)