Let's say I'm working with an object whose inner structure is unknown to me because I didn't create it. For instance, I have a reference to an object called attributes
that contains HTML attributes. I then made a shallow copy of it and froze it using Object.freeze({...attributes}).
I attempted to define its shape as follows:
interface HTMLAttributes = Readonly<{
[attribute: string]: string
}>
or
interface HTMLAttributes = {
readonly [attribute: string]: string
}
However, I still can't get the expected error when directly assigning
attributes.class = '<stuff>'
.
The assignment
attributes['class'] = '<stuff>'
throws the error as expected.
Here's an example (view it on the TypeScript Playground):
interface Example {
readonly [attribute: string]: string
}
var x: Example = {};
x['test'] = 'foo'; // Error: Permits only reading
x.test = 'foo'; // No Error