#How to safely index with string an object that might be `undefined`?

23 messages · Page 1 of 1 (latest)

round gazelle
#
const value = someObject['something'];
// someObject might be `undefined` or of type `{something: string}`
wild cloak
#

there is nothing unsafe about doing someObject['something']

#

what's unsafe is what you do with value

round gazelle
#

here currentExperiment is that someObject

wild cloak
#

simply make sure currentExperiment isn't undefined

#

once you know it's not undefined, the you can access the property you want

round gazelle
#

is there a simple way to do that? kind of like someObject?.something but with indexing?

wild cloak
#

you could also do that, yes

#

there is nothign TypeScript-specific about that

#

it would be the exact same code in plain JS

round gazelle
#

alright, thanks

wild cloak
#
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

round gazelle
round gazelle
wild cloak
wild cloak