I have this code:
class Label{
constructor(
public name:string='name',
public configPath:string='path',
public foo:{bar:string} = {bar:'hello'}
){
}
}
const labelName:string = 'bob'
const configPath:string = './path/to/a/config.file'
const label_name = new Label(labelName, configPath);
function line(line: string):void {
const regex = /\./g;
let path = line.split(regex);
let startingObj = label_name;
function addPath(path: string) {
startingObj = startingObj[path];
}
path.forEach(addPath);
console.log(startingObj);
}
line('name')
line('foo.bar')
line is an input that I want to use to log elements via a terminal request. I imagine it is pretty dangerous way to access the members of a class, it is something that I plan to use during development. line should have this format: report.q1, an I should be able to log the values in the console.
Ts is complaining about startingObj = startingObj[path]; with this error
Element implicitly has an 'any' type because expression of type 'string' >can't be used to index type 'Label'. No index signature with a parameter of >type 'string' was found on type 'App'.ts(7053)
I created a playground to explain what I am trying to do =).
What can I do to get rid of this error?
startingObjectstarts as aLabelbut then becomes other types, and TS doesn't model or track mutation like this. Splitting strings by dots also won't result in strongly typed string literals. If you just want to suppress the error and move on, you can annotatestartingObjectas theanytype to stop the compiler from caring much about what you do with it, like this. Normally I wouldn't recommend usingany, but in this case I don't think there's much better.