首页 > 解决方案 > 如何在打字稿中引用命名空间作为类型

问题描述

google-map-react为我加载谷歌地图库。但是加载的库没有类型信息。
它只是将其返回为any,如下所示。

function onLoadGoogleMap(): { maps: any } {
    return {
        maps: google.maps
    }
}

所以我@types/googlemaps自己安装了。然后我想像这样设置类型信息。但它给了我的错误Namespace 'google' has no exported member 'maps'.

function main() {
    // maps is loaded as any
    const { maps } = onLoadGoogleMap()
    // I want type information, BUT this show me a error.
    const googleMaps: {
        maps: google.maps
    } = {
        maps: maps,
    }

    new googleMaps.maps.LatLng(12, 32)
}

我发现了它的@types/googlemaps样子。这与此类似。

declare namespace google.maps {
    class LatLng {
        constructor(lat: number, lng: number)
    }
}

如何设置命名空间的类型信息?
游乐场在这里。

操场

感谢您的阅读。

标签: reactjstypescriptgoogle-maps

解决方案


我找到了解决这个问题的方法。

@types/googlemaps是一组定义,但打字稿中的命名空间更像是对象。
这篇文章是了解打字稿中的命名空间的好资源。

所以我们可以使用typeof关键字来引用命名空间类型,如下所示。

const googleMaps: {
    maps: typeof google.maps
} = {
    maps: maps,
}

操场


推荐阅读