#Assign the undefined/null check result to a variable and the use such variable as a guard

5 messages · Page 1 of 1 (latest)

faint grailBOT
#
impe#4811

Preview:```ts
interface Stuff {
something?: string
}

function doStuff(value: string) {
return value
}

const obj: Stuff = {}

const hasValue = Boolean(obj.something)
if (hasValue) {
doStuff(obj.something)
}```

gaunt island
#

is there a way to make this work or do I need to check this inline every time?

lofty sphinx
#

@gaunt island The pattern I'd generally suggest is instead of having a boolean that indicates the state of another variable, have a variable that's either the type you expect or undefined.

#
const maybeSomething = Boolean(obj.something) ? obj.something : undefined
if (maybeSomething) {
    doStuff(maybeSomething)
}

This version is kind of silly because maybeSomething is basically the same as just using if(obj.something) inline, which is realistically what I would do in this case.

#

But for more complex forms of validation, this sort of pattern is useful.