gpt4 book ai didi

javascript - 将带有 Promise 的函数从 JS 转换为 TS 时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 03:00:24 26 4
gpt4 key购买 nike

我正在尝试将 NodeJS JavaScript 代码转换为 TypeScript NodeJS 基础,然后在 NodeJS 运行时将其转换为 JavaScript。帮助我保持类型清晰以及 JavaScript 缺少的其他一些有用的东西。

我有一个函数,我调用它来对地址进行地理编码,该函数在 JavaScript 中工作正常,但在 typescript 中我收到错误,它不是一个函数。

import * as googleMapsClient from "@google/maps";

googleMapsClient.createClient({ key: "AIzaSyC0HCjjidjijijes1sbMLG5k"});
export function geocodeAddress( address) {
return new Promise((resolve) => {
googleMapsClient.geocode({
address
}, (err, response) => {
if (!err) {
resolve(response.json.results[0]);
}
});
});
}

在 JavaScript 中工作的相同代码如下所示

const googleMapsClient = require('@google/maps').createClient({
key: 'AIzaSyC0HC2Turfkrofrofkroes1sbMLG5k'
});


function geocodeAddress(address){
return new Promise(resolve =>{
googleMapsClient.geocode({
address: address
}, function(err, response) {
if (!err) {
//console.log(response.json.results[0].geometry)

resolve(response.json.results[0])
}
})
})}


module.exports = {
geocodeAddress :geocodeAddress
}

在 typeScript 中,它提示 Promise

TypeError: googleMapsClient.geocode is not a function
at Promise (C:\nodeRoot\CRMLS-IMPORT\dist\helper\geocoding.js:27:26)
at new Promise (<anonymous>)
at Object.geocodeAddress (C:\nodeRoot\CRMLS-IMPORT\dist\helper\geocoding.js:26:12)
at Object.<anonymous> (C:\nodeRoot\CRMLS-IMPORT\dist\app.js:107:38)
at Generator.next (<anonymous>)
at C:\nodeRoot\CRMLS-IMPORT\dist\app.js:7:71
at new Promise (<anonymous>)
at __awaiter (C:\nodeRoot\CRMLS-IMPORT\dist\app.js:3:12)
at app.get (C:\nodeRoot\CRMLS-IMPORT\dist\app.js:105:40)
at Layer.handle [as handle_request] (C:\nodeRoot\CRMLS-IMPORT\node_modules\express\lib\router\layer.js:95:5)

最佳答案

在 JS 中,您将 createClient() 的返回值分配给 googleMapsClient:

const googleMapsClient = require('@google/maps').createClient({
key: 'AIzaSyC0HC2Turfkrofrofkroes1sbMLG5k'
});

在 TS 中,您将模块的导出分配给 googleMapsClient:

import * as googleMapsClient from "@google/maps";

在 JS 版本中,您可以调用 googleMapsClient.geocode(),因为该函数存在于 createClient() 返回的客户端对象中。

在 TS 版本中,您无法调用 googleMapsClient.geocode(),因为 googleMapsClient 不是客户端对象,而是模块。

将您的 TS 更改为:

import * as googleMaps from "@google/maps";
const googleMapsClient = googleMaps.createClient({
key: 'AIzaSyC0HC2Turfkrofrofkroes1sbMLG5k'
});

关于javascript - 将带有 Promise 的函数从 JS 转换为 TS 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58401555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com