1

I'm translating Java code into TypeScript and I've come across something I can't understand. I've create here object literal name a and I manage to use it as associative array. Then I've define class Node and create variable name n, when I try to use the variable n as key to the associative array the tsc compiler fail with Illegal property access. If I convert n variable to kk variable of type any everything works.

Why is that?

var a = {}
a['a'] = 3
a[4] = 5

class Node {

}
var n:Node = new Node();
a[n] = 44;  <---- Illegal property access

var kk: any = n;
a[kk] = 55

1 Answer 1

2

In this statement:

a[n] = 44;

a is an object.

n is an instance of the Node class.

So you are trying to use a class as the key to a property on the a object.

When you use kk, which is an any type, TypeScript will assume that you know what you are doing and will assume that it will be a string or number at runtime. This is really ignoring the problem.

You could use the type of the n variable, which is a string:

a[typeof n]
Sign up to request clarification or add additional context in comments.

1 Comment

I see. using typeof is not the answer. I have getId function on the Node class so I'll use n.getId(). I guess I just forgot it is javascript after all so there are no real associative array.

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.