问题描述
我写了这段代码
interface Foo {abcdef:数字;}让 x: Foo |细绳;如果(x 实例的 Foo){//...}
但是 TypeScript 给了我这个错误:
'Foo' 仅指一种类型,但在此处用作值.
为什么会这样?我认为 instanceof
可以检查我的值是否具有给定的类型,但 TypeScript 似乎不喜欢这样.
instanceof
使用类,而不是接口.
发生了什么
问题在于 instanceof
是来自 JavaScript 的构造,在 JavaScript 中,instanceof
期望右侧操作数有一个 value.具体来说,在 x instanceof Foo
中,JavaScript 将执行运行时检查以查看 Foo.prototype
是否存在于 x
的原型链中.>
然而,在 TypeScript 中,interface
s 没有发射.这意味着 Foo
和 Foo.prototype
在运行时都不存在,所以这段代码肯定会失败.
TypeScript 试图告诉您这永远行不通.Foo
只是一个类型,它根本不是一个值!
"我可以做什么来代替 instanceof
?"
您可以查看类型保护和用户定义的类型保护.
"但是如果我只是从 interface
切换到 class
呢?"
您可能很想从 interface
切换到 class
,但您应该意识到,在 TypeScript 的结构类型系统中(其中的事情主要是基于形状的),您可以生成与给定类具有相同形状的任何对象:
class C {a:数字=10;b: 布尔值 = 真;c:字符串=你好";}让 x = 新 C()让 y = {a: 10, b: true, c: 你好",}//有效!x = y;y = x;
在这种情况下,您的 x
和 y
具有相同的类型,但是如果您尝试在其中任何一个上使用 instanceof
,您会得到相反的结果.因此,如果您利用 TypeScript 中的结构类型,instanceof
不会真正告诉您关于类型的太多信息.
I wrote this code
interface Foo {
abcdef: number;
}
let x: Foo | string;
if (x instanceof Foo) {
// ...
}
But TypeScript gave me this error:
'Foo' only refers to a type, but is being used as a value here.
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
works with classes, not interfaces.
What's going on
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
.
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 is trying to tell you this could never work. Foo
is just a type, it's not a value at all!
"What can I do instead of instanceof
?"
You can look into type guards and user-defined type guards.
"But what if I just switched from an interface
to a class
?"
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;
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' 仅指一种类型,但在此处用作值."?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!