简体   繁体   中英

What's the correct return type for this TypeScript function?

This is probably a basic TypeScript understanding question.

Google Cloud samples use JavaScript. I'm trying to convert one to TypeScript.

From: https://cloud.google.com/storage/docs/listing-buckets#storage-list-buckets-nodejs

The JS code is:

// 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);

The type definitions for getBuckets are:

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

And the type definition for GetBucketsResponse is:

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

I don't know what return value to use. If I set the return type to Bucket[] , it fails with The return type of an async function or method must be the global Promise<T> type.

And if I try async function listBuckets(): Promise<Bucket[]> , it fails on the return, saying Type '() => Promise<Bucket[]>' is missing the following properties from type 'Bucket[]': pop, push, concat, join, and 25 more.

Your are not returning anything from function, So return 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);
  });
}

It is already promise, you dont need to create promise again.

// Creates a client 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM