Mapbox-gl类型不允许accessToken分配 [英] Mapbox-gl typing won't allow accessToken assignment

查看:1504
本文介绍了Mapbox-gl类型不允许accessToken分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有TypeScript的mapbox-gl库,并且已经使用@types/mapbox-gl安装了它的社区源类型定义.当我尝试导入并设置一个accessToken以使用该库时,我的TypeScript编译器抛出此错误: TS2540: Cannot assign to 'accessToken' because it is a constant or a read-only property.

I'm using the mapbox-gl library with TypeScript, and I've installed its community sourced type definitions with @types/mapbox-gl. When I try to import and set an accessToken to use the library, my TypeScript compiler throws this error: TS2540: Cannot assign to 'accessToken' because it is a constant or a read-only property.

所以我拉出.d.ts文件,所讨论的变量看起来非常可赋值(请参见此处:

So I pulled up the .d.ts file and the variable in question looks extremely assignable (seen here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/mapbox-gl/index.d.ts):

declare namespace mapboxgl {
   let accessToken: string;
   ...

这是我的代码:

import * as mapbox from 'mapbox-gl';
mapbox.accessToken = 'token';

版本!

"@types/mapbox-gl": "^0.35.0",
"typescript": "^2.3.4",
"mapbox-gl": "^0.37.0",

TypeScript hackery说我可以将mapbox投射到任何对象上,并且可以使用,但是我很好奇这里的键入有什么问题.

TypeScript hackery says that I can cast mapbox to any and it will work, but I'm very curious what about the typing is going wrong here.

推荐答案

这是我一直在使用的临时解决方法:

Here's a temporary workaround I've been using:

Object.getOwnPropertyDescriptor(mapboxgl, "accessToken").set('YOUR_TOKEN');

说明

由于该对象被重新定义为使用自定义设置器,该自定义设置器将令牌放置在内部闭包内-我们可以直接调用setter函数,如示例所示.

Explanation

Since the object was redefined to use a custom setter which places the token inside an internal closure - we can call the setter function directly as shown in the example.

再深入一点,我们可以看到es6模块在定义上是常量: https://github.com/Microsoft/TypeScript/issues/6751#issuecomment-177114001

Diving a little deeper, we can see that es6 modules are constants by definition: https://github.com/Microsoft/TypeScript/issues/6751#issuecomment-177114001

然后我们可以做类似的事情:(mapboxgl as any).accessToken = ...会起作用的.

we can then do something like: (mapboxgl as any).accessToken = ... which will work.

这篇关于Mapbox-gl类型不允许accessToken分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆