3

There is a way to declare the type of dynamic class property if it's accessed by [] operator, like on the following example:

class Foo {
  [key: string]: number;
}

let a = new Foo();
let b = a['bar']; //Here, the compiler knows that b is a number

But is there a way to declare the same thing, without [] operator? A way to write this:

let a = new Foo();
let b = a.someProperty;

And letting TypeScript knows that someProperty is of type number, because we say to it: All unknown properties on Foo are of type number.

1 Answer 1

2

I do not think its is possible. When you define class you define 'static' information about its properties and methods. If you specify indexer - it means just that - that the objects of the class will have indexer, not any properties. Thats what classes are for after all - to define structure of your business entities.

The only way I am aware of doing something similar to what you want is by using object literals. For example this will work:

let x: { PropA: number, [x: string]: number };
x = { PropA: 1, PropX: 2, PropY: 3, PropZ: 4 };

Hope this helps.

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

1 Comment

I totally agree with your point, classes are here to define a structure and I'm not surprised it's not possible, because it doesn't make a lot of sense. By the way, your suggestion about object literals might help, because at some point during my application lifetime, I have information about these dynamic properties, so maybe I could do something hackish with that. Thanks!

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.