Hacker News new | ask | show | jobs
by wdfx 1710 days ago
The type itself is fine but how it is checked and used is not. The following would be better, and in this case you will also have a Human type inside the forEach callback:

    // ... other code

    type Human = { name: string; age: number }

    const isHuman = (obj: unknown): obj is Human => obj && typeof obj === 'object' && 'name' in obj && 'age' in obj; // you can complete the gaps here and also check the property types

    someArray.filter(isHuman).forEach((h) => {
      // h has type Human now
      console.log(h.age);
    })
2 comments

This is reasonable for validating an untrusted object, sure, but I don't recall that constraint being expressed as part of what the original post was addressing.
The type guard may be useful when transferring that array server->client or vice versa, or for an array from any other untrusted source, but I don’t think that was the purpose of the demo in the article. When the array in question is coming from the same code base that kind of runtime type check is redundant.