0

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..

1 Answer 1

1

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`)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.