1

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?

0

1 Answer 1

1

Using the array function, the signature provides that the array is a record holder and not x and y itself.

For example:

const list = [x, y];
if (areRecords(list)) {
    // Now typescript knows that list is Record<string, any>[];
    // However, it does not know what x and y is, because
    // the function signature only refers to the array.
}

What you can do is:

const list = [x, y];
if (areRecords(list)) {
    list.forEach(item => console.log(item["att"]));
}

or:

const attributes = [x, y].filter(isRecord).map(value => value["att"]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.