【问题标题】:How to get lodash from window?如何从窗口获取 lodash?
【发布时间】:2018-07-24 11:20:09
【问题描述】:

在纯 JS 中我有代码

const { _ } = window;

现在我将项目迁移到 Typescript 2.8 并导致错误:

错误 TS2459:类型 'Window' 没有属性 '_' 并且没有字符串索引签名。

tsconfig:

{
  'allowJs': true,
  'allowSyntheticDefaultImports': true,
  "target": "es2017",
  "baseUrl": "src",
  'resolveJsonModule': true,
  'noImplicitAny': false
}

PS:我无法通过代码中的导入来使用 lodash。

【问题讨论】:

  • 一种快速而肮脏的方式是const _ = (window as any)._ as _;,但我不确定这是否是“最好”/“最干净”的方式。
  • @AndyJ 至少它有效。现在我有错误“错误 TS2686:'_' 指的是一个 UMD 全局,但当前文件是一个模块。考虑添加一个导入。”
  • 尝试使用const _ = window["_"];
  • @KoushikChatterjee 首先经过测试 - 不起作用

标签: typescript lodash typescript-typings


【解决方案1】:

要使用 typescript 在窗口上将 lodash 作为“_”,您可能需要执行以下操作:

import {LoDashStatic} from 'lodash'   // import the library
declare let window: {                 // declare the type for window
  _: LoDashStatic;                    // (we'd add jquery like so too)
}     
const {_} = window;                   // create the convenient constant

_.range(1, 3);                         // works now w/o compile error

【讨论】:

    猜你喜欢
    • 2011-10-14
    • 1970-01-01
    • 2019-09-22
    • 2012-01-19
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多