在ActionScript中,可以在运行时使用is操作符检查类型:

var mySprite:Sprite = new Sprite(); 
trace(mySprite is Sprite); // true 
trace(mySprite is DisplayObject);// true 
trace(mySprite is IEventDispatcher); // true

是否有可能检测一个变量(扩展或)是TypeScript的某个类或接口?

我在语言规范里找不到任何关于它的信息。在处理类/接口时,它应该存在。


4.19.4操作符的实例 instanceof操作符要求左操作数为Any类型,对象类型或类型形参类型,右操作数为Any类型或'Function'接口类型的子类型。结果总是布尔基元类型。

所以你可以用

mySprite instanceof Sprite;

注意,这个操作符也在ActionScript中,但不应该再使用了:

The is operator, which is new for ActionScript 3.0, allows you to test whether a variable or expression is a member of a given data type. In previous versions of ActionScript, the instanceof operator provided this functionality, but in ActionScript 3.0 the instanceof operator should not be used to test for data type membership. The is operator should be used instead of the instanceof operator for manual type checking, because the expression x instanceof y merely checks the prototype chain of x for the existence of y (and in ActionScript 3.0, the prototype chain does not provide a complete picture of the inheritance hierarchy).

TypeScript的instanceof也有同样的问题。由于这是一门仍处于发展阶段的语言,我建议你提出这样一项建议。

参见:

MDN:运算符

TypeScript有一种在运行时验证变量类型的方法。 可以添加返回类型谓词的验证函数。 因此,您可以在if语句中调用此函数,并确保该块中的所有代码都可以安全地作为您认为的类型使用。

来自TypeScript文档的例子:

function isFish(pet: Fish | Bird): pet is Fish {
   return (<Fish>pet).swim !== undefined;
}

// Both calls to 'swim' and 'fly' are now okay.
if (isFish(pet)) {
  pet.swim();
}
else {
  pet.fly();
}

更多信息请访问: https://www.typescriptlang.org/docs/handbook/advanced-types.html

您可以为此使用instanceof操作符。中数:

的原型属性是否为 构造函数出现在对象的原型链中的任何地方。

如果你不知道原型和原型链是什么,我强烈建议你去查一下。这里还有一个JS (TS在这方面的工作类似)的例子,可以澄清这个概念:

class Animal { name; constructor(name) { this.name = name; } } const animal = new Animal('fluffy'); // true because Animal in on the prototype chain of animal console.log(animal instanceof Animal); // true // Proof that Animal is on the prototype chain console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true // true because Object in on the prototype chain of animal console.log(animal instanceof Object); // Proof that Object is on the prototype chain console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true console.log(animal instanceof Function); // false, Function not on prototype chain

本例中的原型链为:

动物。Object.prototype

你有两种支票

Typeof用于基本类型和 Instanceof用于复杂类型

通过ex, isString检查可以这样执行:

function isString(value) {
    return typeof value === 'string' || value instanceof String;
}

尽管已经有了一些好的答案。@Gilad提出的解决方案有缺陷,如果分配的内容游泳存在类型,但值被设置为未定义。一个更有力的检查应该是:

export const isFish= (pet: Fish | Bird): pet is Fish =>
   Object.keys(pet).includes('swim');

这个解决方案不依赖于swim的值!