我写了这段代码
interface Foo {
abcdef: number;
}
let x: Foo | string;
if (x instanceof Foo) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是TypeScript给了我这个错误:
'Foo' only refers to a type, but is being used as a value here.
Run Code Online (Sandbox Code Playgroud)
为什么会这样?我认为instanceof
可以检查我的值是否具有给定类型,但TypeScript似乎不喜欢这样.
我正在尝试为我的 React 组件编写一个测试,使用 TypeScript、Jest 作为我的测试运行程序和 Enzyme 来测试我的 React 组件。每当我将我的组件传递给shallow
Enzyme 函数时,我都会收到 ts 错误“'Navbar' 指的是一个值,但在此处被用作类型。”,并且在下面我收到 eslint 错误“解析错误:'>' 预期” .
我在其他一些组件上尝试过,当shallow
作为参数传递给函数时,所有组件都出现相同的错误。我怀疑这可能与我的 TS 配置有关,但对于我的生活,我似乎无法找到解决方案。
这是 Navbar.tsx 的代码:
import React from 'react';
import { shallow } from 'enzyme';
import Navbar from './Navbar';
describe('Navbar component', () => {
let component;
beforeEach(() => {
component = shallow(<Navbar />); // Error being desplayed here
});
it('should render without errors', () => {
expect(component).toMatchInlineSnapshot();
expect(component.length).toBe(1);
expect(component).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
还发布我的配置文件:
配置:
{
"compilerOptions": {
"target": "es5", …
Run Code Online (Sandbox Code Playgroud) 我有一段TypeScript代码,我很难理解.我是TypeScript的新手.
export const TerminalWidgetOptions = Symbol("TerminalWidgetOptions");
export interface TerminalWidgetOptions {
endpoint: Endpoint.Options,
id: string,
caption: string,
label: string
destroyTermOnClose: boolean
}
Run Code Online (Sandbox Code Playgroud)
有人能告诉我上面的代码究竟发生了什么?我所理解的是,名字的接口TerminalWidgetOptions
被创建,它迫使参数endpoint
,id
,caption
,label
和destroyTermOnClose
在实施成一类.我虽然不太了解上述内容.所以,显然创建了一个常量,只能设置一次然后保持这种状态,对吧?但是这个常量怎么能和接口类型同名呢?任务Symbol("TerminalWidgetOptions");
很明确.来自Symbol函数的内容被放入常量中.
这或多或少是正确的吗?