demo:
function getValue(data: unknown) {
// return data?.value // error
// or
// use "value" in data to narrow the scope
if (typeof data === 'object' && data && 'value' in data) {
return data.value; // error
}
return '';
}
I don't want to use assertions data is similar to the data returned by a request
return data?.value ?? '';
?in
operator very well at the moment. Either use type assertions or you could write a type guard likeconst hasValue = (obj: any): obj is {value: unknown} => typeof obj === 'object' && obj && 'value' in obj
and then use itif(hasValue(data))