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)
}```
5 messages · Page 1 of 1 (latest)
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)
}```
is there a way to make this work or do I need to check this inline every time?
@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.