繁体   English   中英

如何使用 `instanceof` 为 typescript 中的自定义类型数组创建类型保护?

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

假设我有一堆狗:

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

如何使用instanceof运算符区分一组狗和一组猫?

我已经尝试了一些东西,但它们都给我 typescript 我不明白的错误,所以我认为我缺少正确的语法,我找不到任何人在任何地方这样做的例子。

// 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>[]) {

我知道还有其他方法可以在运行时保证数组确实充满了狗,但我对进行深入的反省不感兴趣——我只想编写一个instanceof类型保护并调用很好,但我显然遗漏了一些东西。

您可以使用返回类型断言值的函数,但我认为它不适用于泛型。

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')
}

我是ts-narrow library 的作者,我在这里想出了这个解决方案:

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

您可以检查存储库中的文件 isInstanceOf.ts,以及其他高级窄函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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