#How to safely index with string an object that might be `undefined`?
23 messages · Page 1 of 1 (latest)
there is nothing unsafe about doing someObject['something']
what's unsafe is what you do with value
but it doesn't let me
here currentExperiment is that someObject
simply make sure currentExperiment isn't undefined
once you know it's not undefined, the you can access the property you want
is there a simple way to do that? kind of like someObject?.something but with indexing?
you could also do that, yes
there is nothign TypeScript-specific about that
it would be the exact same code in plain JS
alright, thanks
interface Experiment {
something: unknown;
}
declare const currentExperiment: Experiment | undefined;
const something = currentExperiment?.something;
// or
if(currentExperiment) currentExperiment.something;
also, as a sidenote, we typically don't prefix interfaces with I in typescript
since there is no difference between an interface, type, class, object at the type level
it's all the same type
you see, the first option is good, but the something key can change frequently in my case and i am going to use this at a lot of places in my code. so i want to index it with a constant so that i can change it at one place. and i also don't want it be an if else or ternary otherwise it might get messy.
ik, that's something past developers from my team didn't know 🗿
you can also do optional chaining with indexed access
someObject?.[someKey]
would then make some kind of singleton, or some kind of getter in a module to get the property
perfect, thank you.