问题描述
我写了这段代码
interface Foo {
abcdef: number;
}
let x: Foo | string;
if (x instanceof Foo) {
// ...
}
但是TypeScript给了我这个错误:
But TypeScript gave me this error:
'Foo' only refers to a type, but is being used as a value here.
为什么会这样?我以为instanceof
可以检查我的值是否具有给定类型,但是TypeScript似乎不喜欢这样.
Why is this happening? I thought that instanceof
could check whether my value has a given type, but TypeScript seems not to like this.
推荐答案
instanceof
适用于类,而不适用于接口.
instanceof
works with classes, not interfaces.
问题在于 instanceof
是JavaScript的构造,在JavaScript中,instanceof
期望右侧操作数为 value .具体来说,在x instanceof Foo
中,JavaScript将执行运行时检查,以查看Foo.prototype
原型链中是否存在Foo.prototype
.
The issue is that instanceof
is a construct from JavaScript, and in JavaScript, instanceof
expects a value for the right-side operand.Specifically, in x instanceof Foo
JavaScript will perform a runtime check to see whether Foo.prototype
exists anywhere in the prototype chain of x
.
但是,在TypeScript中,interface
没有发出.这意味着Foo
和Foo.prototype
在运行时都不存在,因此该代码肯定会失败.
However, in TypeScript, interface
s have no emit. That means that neither Foo
nor Foo.prototype
exist at runtime, so this code will definitely fail.
TypeScript试图告诉您这可能永远不会. Foo
只是一种类型,根本不是值!
TypeScript is trying to tell you this could never work. Foo
is just a type, it's not a value at all!
您可以查看类型保护器和用户定义的类型保护器.
您可能会很想从interface
切换到class
,但是您应该意识到,在TypeScript的结构类型系统(主要基于 shape 的结构)中,您可以生成任何与给定类具有相同形状的对象:
You might be tempted to switch from an interface
to a class
, but you should realize that in TypeScript's structural type system (where things are primarily shape based), you can produce any an object that has the same shape as a given class:
class C {
a: number = 10;
b: boolean = true;
c: string = "hello";
}
let x = new C()
let y = {
a: 10, b: true, c: "hello",
}
// Works!
x = y;
y = x;
在这种情况下,您的x
和y
具有相同的类型,但是如果您尝试在任何一个上使用instanceof
,则在另一个上会得到相反的结果.因此,如果您要利用TypeScript中的结构类型,instanceof
不会真正告诉您有关类型的更多信息.
In this case, you have x
and y
that have the same type, but if you try using instanceof
on either one, you'll get the opposite result on the other. So instanceof
won't really tell you much about the type if you're taking advantage of structural types in TypeScript.
这篇关于为什么TypeScript中的"instanceof"会给我错误“"Foo"仅指代一种类型,但在此处被用作值".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!