My current approach involves a function that validates if a variable is an object and not null:
function isRecord(input: any): input is Record<string, any> {
return input !== null && typeof input === 'object';
}
This type predicate is essential for TypeScript to accept the following code snippet:
if (isRecord(x)) {
console.log(x["att"]);
}
I also created another function that operates on arrays, but I am encountering an error stating "Object is possibly 'null'":
function areRecords(list: any[]): list is Record<string, any>[] {
return list.every(element => isRecord(element));
}
if (areRecords(x, y)) {
console.log(x["att"]);
console.log(y["att"]);
}
The same error persists even if I remove the "is" keyword:
function areRecords2(list: any[]): boolean {
return list.every(element => isRecord(element));
}
if (areRecords2([x, y])) {
console.log(x["att"]);
console.log(y["att"]);
}
An alternative attempt using rest parameters has also not resolved the issue:
function areRecords3(...list: any[]): boolean {
return list.every(element => isRecord(element));
}
if (areRecords3(x, y)) {
console.log(x["att"]);
console.log(y["att"]);
}
I am seeking guidance on how to correct this. What would be the right way to handle this situation?