在类型打字稿中定义类类型

时间:2020-06-14 09:51:11

标签: typescript

我在我的一个项目中使用ts,并且有点像初学者:

我有这样的东西

import * as admin from "firebase-admin";
import { Request } from "express";

export interface FileStorage {
  storage: admin.storage.Storage;
  rootBucket: any,
  bucketName: string | undefined;
}

export class FileStorage implements FileStorage {
  constructor() {
    this.storage = admin.storage();
    this.rootBucket = this.storage.bucket();
    this.bucketName = admin.instanceId().app.options.storageBucket;
  }

在上面的代码片段中,我的rootBucket的类型为any。我希望它更加精确:

这是存储的界面

  interface Storage {
    /**
     * Optional app whose `Storage` service to
     * return. If not provided, the default `Storage` service will be returned.
     */
    app: admin.app.App;
    /**
     * @returns A [Bucket](https://cloud.google.com/nodejs/docs/reference/storage/latest/Bucket)
     * instance as defined in the `@google-cloud/storage` package.
     */
    bucket(name?: string): Bucket;
  }
}

如果我在Bucket上cmd + click,那么它将用u

declare class Bucket extends ServiceObject {

您可以在github上找到声明类Bucket here

1 个答案:

答案 0 :(得分:1)

在您的情况下,您可以跳过接口并直接在类中声明成员变量。 您可以从库中导入Bucket类并在您的类中使用它:

import * as admin from "firebase-admin";
import { Bucket } from "@google-cloud/storage"

export class FileStorage {
  storage: admin.storage.Storage = admin.storage();
  rootBucket: Bucket;
  bucketName: string | undefined;

  constructor() {
    this.rootBucket = this.storage.bucket();
    this.bucketName = admin.instanceId().app.options.storageBucket;
  }