此 TypeScript 函数的正确返回类型是什么?



这可能是一个基本的TypeScript理解问题。

Google Cloud示例使用JavaScript。我正在尝试将一个转换为TypeScript。

发件人:https://cloud.google.com/storage/docs/listing-buckets#storage-列出存储桶nodejs

JS代码为:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');
// Creates a client
const storage = new Storage();
async function listBuckets() {
// Lists all buckets in the current project
const [buckets] = await storage.getBuckets();
console.log('Buckets:');
buckets.forEach(bucket => {
console.log(bucket.name);
});
return listBuckets;
}
listBuckets().catch(console.error);

getBuckets的类型定义为:

getBuckets(options?: GetBucketsRequest): Promise<GetBucketsResponse>;
getBuckets(options: GetBucketsRequest, callback: GetBucketsCallback): void;
getBuckets(callback: GetBucketsCallback): void;

GetBucketsResponse的类型定义是:

export declare type GetBucketsResponse = [Bucket[], {}, Metadata];

我不知道该使用什么返回值。如果我将返回类型设置为Bucket[],则The return type of an async function or method must be the global Promise<T> type.失败

如果我尝试async function listBuckets(): Promise<Bucket[]>,它在返回时失败,说Type '() => Promise<Bucket[]>' is missing the following properties from type 'Bucket[]': pop, push, concat, join, and 25 more.

您没有从函数返回任何内容,因此返回Promise<void>

async function listBuckets(): Promise<void> {
// Lists all buckets in the current project
const [buckets] = await storage.getBuckets();
console.log('Buckets:');
buckets.forEach(bucket => {
console.log(bucket.name);
});
}

它已经是承诺,你不需要再创造承诺。

//创建客户端const-storage=new storage((;

function listBuckets() {
// Lists all buckets in the current project
return storage.getBuckets().then((buckets) => {
console.log('Buckets:');
buckets.forEach(bucket => {
console.log(bucket.name);
});
return buckets
});
}
listBuckets().catch(console.error);

最新更新