2

The problem is simple, in javascript I can have an object as this one

var obj={
    par1:'value1',
    par2:'value2'
}

And I can access to the values in this ways obj['par1'] is it possible to do the same thing in TypeScript with a class like this:

export class obj{
    par1:string;
    par2:string;
}

this.obj['par1']=value1

Update

This is the Documents class

export class Documents {
    par1: string
    par2: string
    constructor(par1: string,
        par2: string
    ){
        this.par1=par1
        this.par2=par2
    }
}

And this is my attempt:

private docs:Documents[]=new Documents[
    new Documents('value1','value2'),
    new Documents('value3','value4')
];
sort(ordertype:string,property:string){
    for(let doc of this.docs){
        for(let field in doc)
            console.log(doc[field])
    }
}

And this is an error:

[ts] Element implicitly has an 'any' type because index expression is not of type 'number'.

I've even tried to cast it to string but nothing.

Update 2

I've saw the error, I corrected it, the code above is correct and works.

4
  • Did you try it? Are you getting any errors? Commented Jul 26, 2016 at 13:12
  • where instance of this class created? Commented Jul 26, 2016 at 13:39
  • Ok sorry it was a generic question, in attempt to get some information on typescript and understand the difference between the javascript objects an typescript classes Commented Jul 26, 2016 at 13:58
  • done it and the exception is the same. Commented Jul 26, 2016 at 14:16

2 Answers 2

2

You don't create the Documents array properly, it should be like this:

let docs: Documents[] = [];
docs.push(new Documents('value1', 'value2'));
docs.push(new Documents('value3', 'value4'));

or

let docs: Documents[] = [new Documents('value1', 'value2'), new Documents('value3', 'value4')];

If you do that then your code works fine, check it out in playground.

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

Comments

0

Try replacing console.log(doc[field]) with console.log((doc as any)[field])

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.