I am using a function that checks if a variable is an object and not null with:
function isRecord(input: any): input is Record<string, any> {
return input !== null && typeof input === 'object';
}
The type predicate ist necessary, so typescript accepts:
if (isRecord(x)) {
console.log(x["att"]);
}
I wrote another function that takes an array, but typescript complains with "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 if I omit "is"
function areRecords2(list: any[]): boolean {
return list.every(element => isRecord(element));
}
if (areRecords2([x, y])) {
console.log(x["att"]);
console.log(y["att"]);
}
Or if I use rest parameters:
function areRecords3(...list: any[]): boolean {
return list.every(element => isRecord(element));
}
if (areRecords3(x, y)) {
console.log(x["att"]);
console.log(y["att"]);
}
How to do it right?