gpt4 book ai didi

javascript - 如何使用接口(interface)类型执行动态类型测试?

转载 作者:行者123 更新时间:2023-11-30 00:06:43 26 4
gpt4 key购买 nike

这是一个 SSCCE。下面的代码:

// @flow    
'use strict';

declare interface ICat {
purr(): string;
}

class Animal {
askToBeStrokedAsACat() {
strokeAsACat(this); // Flow complains here
}
}

function strokeAsACat(a: ICat) {
a.purr();
}


class Cat extends Animal {
purr() {
return 'purr';
}
}

const cat = new Cat();
cat.askToBeStrokedAsACat();

... 结果为 Flow提示 strokeAsACat 的函数调用。投诉是(为简洁起见进行了编辑):

property `purr` of ICat not found in class Animal

投诉合理,可以理解。

根据dynamic type tests上写的我应该能够简单地执行以下操作:

class Animal {
askToBeStrokedAsACat() {
if (this instanceof ICat)
strokeAsACat(this);
}
}

... 而不是上面的失败:

ICat. type referenced from value position

另外,由于接口(interface)被转译掉了,ICat 在运行时不可用,所以上面的代码在运行时失败:

ReferenceError: ICat is not defined

因此,确定此时的 this 句柄是一个类似 ICat 的对象的唯一方法是执行以下操作:

class Animal {
askToBeStrokedAsACat() {
if (this instanceof Cat)
strokeAsACat(this);
}
}

... 但这是 nominal, not structural typing并且违背了使用接口(interface) ICat 的目的,就好像我添加了更多的 ICat-like 类一样,我必须将动态类型测试编写为:

(this instanceof Cat) || (this instanceof BobCat) || (this instanceof Lynx)

所以我的问题是:

  1. 有没有办法对 interface 执行结构动态类型测试?
  2. 是否有其他方法可以有效消除 Flow 对该特定线路的投诉?

我的 Flow 版本是:

$ npm ls --depth 0 | grep flow-bin
├── flow-bin@0.27.0

最佳答案

is there a way to perform a structural dynamic type test for interface

不,这是不可能的。您可以测试该对象是否具有属性并且它是一个函数,但您如何知道它在运行时的签名?

不过,您应该很少需要它。例如,在您的代码中,您可以将 Animal 上的 askToBeStrokedAsACat 留空,并在 Cat 子类中覆盖它。

关于javascript - 如何使用接口(interface)类型执行动态类型测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38229196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com