I was wondering if it is possible to check for undefined values in object with typescript using helper function?
type Page = {
hero?: {
title?: string
},
about: {
title?: string,
}
}
const obj: Page = {
hero: undefined,
about: {
title: 'hello',
}
}
const check = <T extends Object,>(obj: T, values: Array<keyof T>) => {
values.forEach((value)=>{
if (!obj[value]){
throw new Error(`${value} is missing!`)
}
})
};
check(obj, ['hero'])
obj.hero.title
but it still says that " Object is possibly 'undefined' " . Is there any way I can achieve something like that with typescript?
EDIT: I am aware that I can explicitly check for that property using ? . I wonder if it is possible to make ts happy using helper function as described above.
!obj[value]will throw for any falsey value, not just undefined. If you want to know if it's undefined, you have to compare to undefined.obj.herois not undefined, you can tell the transpiler so likeobj.hero!.titlecheck()is doing an assertion onobj. You could explicitly annotatecheckas an assertion function if you want this behavior. It looks like this. Does that meet your needs? If so I could write up an answer; if not, what am I missing?