1

Where there is no error at this line

            if (!t[1]) {
                t[1] = [];
            }

            t[1].push(key);

t is of type Test, which is not directly indexible. But, it has a member, data, which can be indexed. So why there is no error in these lines.

ITestData models a nested object, with integer and string key respectively.

{ 
  1 : {
        "hello" : {}
  }
  2 : { ..
}

demo

Code:

export interface ITestData {
    [idx:number] : {[prop:string]:any}
}

export interface ITest {
    data:ITestData
}

export class Test implements ITest {
        data:ITestData = {};
}

class Greeter {
    data:ITestData = {};

    private del(t:Test, key:string) {
        if (!t[1]) {
            t[1] = [];
        }

        t[1].push(key);
   }
}

1 Answer 1

1

Everything in JavaScript can be indexed via a string (and number using number.toString()). TypeScript will allow indexing by string (and number).

A simpler version of what you are experiencing :

var foo = {data:123};
var bar = foo[0]; // Valid : bar is of type any 

You can prevent what can be assigned to an indexed member e.g. only Foo can be assigned in the following case when indexed:

var bas: {[index:string]:Foo}; 

But you cannot disable indexing all together (i.e. you can restrict the type of read / write but not the fact that you can read / write).

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

3 Comments

thanks. How to prevent it (how to use index signature with a class?). Or any better way to represent this datastructure?
@bsr I had poor choice of words. Clarified
thanks basarat. I see that typescript is a super set of JS, but class is a concept introduced by TS. IT doesn't make sense to support indexing it. Will be it supported in native ES6 classes, I don't know. But, if it doesn't make logical sense, at least at TS level, the compiler can warn the usage. Do you think it is possible, desired, should be a feature? I also not sure your usage of foo, bas, an object, equivalent to mine, t:Test, a class. Again, may be compile down to a function or whatever, but considering other languages and expectations, it is an odd behavior.

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.