I have a function that receives a string as a parameter. This string should match an object's path, so the function can return a correct value from the requested key.
How to make sure the string path is included in the original object? Also, would it be possible to get an autocomplete while writing the parameter?
For exemple:
const obj = {
"hello": "hello",
"company": {
"employee": {
"tech": "tech team",
"sales": "sales team"
}
},
}
function getString(path: string){
let result = obj
path.split(".").forEach((k) => {
if (!result[k]) return;
return (result = result[k]);
});
return result
}
getString("hello")
// typescript remains silent because the path exists.
getString("howdy")
// typescript returns an error because the path doesn't exist.
getString("company.em")
// autocomplete suggests: company.employee.tech & company.employee.sales
Of course, this function is useless, it's just a simple exemple to keep things focused on the issue.