首页 > 解决方案 > 如何更正错误 win 指的是一个值,但在这里被用作一个类型

问题描述

我在这里按照示例进行操作,并拥有以下 TypeScript 代码:

const { app, BrowserWindow, ipcMain } = require('electron');

let win;

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  // and load the index.html of the app.
  win.loadFile('bin/js-debug/index.html')

  // Open the DevTools.
  //win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}

我将扩展名从 .js 更改为 .ts 并开始显示错误。

我收到这个警告:

变量“win”在无法确定其类型的某些位置隐式具有“any”类型。ts(7034)

所以我尝试像这样添加类型:

let win:BrowserWindow;

我收到这条消息:

'BrowserWindow' 指的是一个值,但在这里被用作一个类型。

笔记:

如果我将类型设置为任何错误就会消失。

let win:any;

标签: typescriptelectron

解决方案


使用 typescript 时,必须使用 typescript 模块导入语法(类似于 ESModule 导入),否则 typescript 不会导入类型并将 BrowserWindow 视为通过定义的变量require()

import { app, BrowserWindow, ipcMain } from 'electron'

推荐阅读