首页 > 解决方案 > TypeScript declare var error for object.property - what to do?

问题描述

There are many ways suggested in SO to dynamically import external scripts such as 'https://something.com/...js' The problem is that TypeScript doesn't know about the properties so it gives errors.

As a work-around TS provides

declare var someObject

and you can put the object you retrieved from the external source in that. This works, no errors. However, it doesn't work for

let variable = someObject.property

The property gives an error because TS has no idea what is in your object.

Does anyone have this solved?

This is some of my actual code and it doesn't work. The error is

Property createUploadWidget does not exist on type 'Scripts' 
interface Scripts {
  name: string;
  src: string;
}

declare var CloudinaryScripts: Scripts;

CloudinaryScripts =
  {name: 'upLoader', src: 'https://widget.cloudinary.com/v2.0/global/all.js'};

export class CloudinaryComponent {
  ...
  private uploadWidget = CloudinaryScripts.createUploadWidget(
    {
      cloudName: ...
}

Also, this creates a big error:

CloudinaryScripts[createUploadWidget]

标签: angulartypescript

解决方案


您可以通过将其定义为 any 来解决该错误

declare var someObject: any

你得到的错误是正确的

“脚本”类型上不存在属性 createUploadWidget(仅存在名称和 src)

interface Scripts {
  name: string;
  src: string;
}

推荐阅读