Here is the code snippet that I am working with:
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')
The purpose of the line
function is to allow me to retrieve and log elements through a terminal request. While I acknowledge that directly accessing class members in this manner may have its risks, for development purposes, I find it suitable. The format for line
should be similar to report.q1
, and the logged values should appear in the console.
When using TypeScript, an error arises with startingObj = startingObj[path];
, specifically:
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)
To provide further clarity, I have set up a demo on the TypeScript playground.
How can I resolve this error in TypeScript?