Sometimes, we want to fix ‘instanceof’ in TypeScript give me the error “’Foo’ only refers to a type, but is being used as a value here.” error.
In this article, we’ll look at how to fix ‘instanceof’ in TypeScript give me the error “’Foo’ only refers to a type, but is being used as a value here.” error.
How to fix ‘instanceof’ in TypeScript give me the error “’Foo’ only refers to a type, but is being used as a value here.” error?
To fix ‘instanceof’ in TypeScript give me the error “’Foo’ only refers to a type, but is being used as a value here.” error, we should only use instanceof
with constructors.
For instance, we write
interface Foo {
abcdef: number;
}
let x: Foo | string;
if ('abcdef' in x) {
// ...
}
to create the Foo
instance.
And we check if x
implements Foo
with 'abcdef' in x
.
If the abcdef
property is in x
, then we know x
is a Foo
object since strings don’t have the abcdef
property and x
is either a Foo
object or a string.
Conclusion
To fix ‘instanceof’ in TypeScript give me the error “’Foo’ only refers to a type, but is being used as a value here.” error, we should only use instanceof
with constructors.