简体   繁体   中英

How do I use `instanceof` to create a type guard for an array of custom types in typescript?

Say I have an array of dogs:

const thePound = new Array<Dog>();
for (let i = 0; i < 10; i++) {
  thePound.push(new Dog(randomDogName()));
}

How do I differentiate an array of dogs from an array of cats using the instanceof operator?

I've tried the a few things but they all give me typescript errors that I don't understand, so I think I'm missing the proper syntax and I can't find any examples of anyone doing this anywhere.

// Is it a dog pound or a cat pound?
function (thePound: Dog[] | Cat[]) {
  // Parsing error
  if (thePound instanceof Array<Dog>) {
  // Syntax error
  if (thePound instanceof Dog[]) {
  // Generic types have issues too
  if (thePound instanceof Dog<Pug>[]) {

I'm aware there are other ways of doing this which guarantee at runtime that the array is indeed filled with dogs, but I'm not interested in doing that deep introspection -- I'd like to simply write an instanceof type guard and call it good, but I'm clearly missing something.

You can use a function returning a type assertion value, but I don't think it works for generics.

interface Dog {
  foo: string
  bar?: number
}

function isDogArray(array: any[]): array is Dog[] {
  // do needed checks, returning true or false
  return array.every(x => typeof x?.foo === 'string')
}

I'm author of ts-narrow library, and I came up with this solution here:

export const isInstanceOf =
  <Target extends Function>(e: Target) =>
  (target: unknown): target is Target["prototype"] =>
    target instanceof e;

You can check file isInstanceOf.ts on the repository, and also other advanced narrow functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM