Insight:
When working with Typescript, it is important to remember that it is a strictly typed language. This means that errors can occur at compile time if the correct types are not used. In the given scenario, using the returned value of prompt()
as an index can lead to potential issues because array indexes cannot be null, while the return value from prompt()
can be null.
To handle this situation, you must specify to the compiler that if fieldName
is null, then use an empty string instead. By doing this, you ensure that the index will never be null.
Here are two alternatives to consider:
onClick(){
let obj={
fName:"ali",
LName:"sarabi",
age:"19",
}
let fieldName = prompt("field") || "";
alert(obj[fieldName]);
}
or try this approach:
onClick(){
let obj={
fName:"ali",
LName:"sarabi",
age:"19",
}
let fieldName = prompt("field");
alert(obj[fieldName?fieldName:""]);
}