【问题标题】:TS typeof in constructor parameter loses type and VSCode auto-complete构造函数参数中的 TS typeof 丢失类型和 VSCode 自动完成
【发布时间】:2021-11-26 03:33:47
【问题描述】:

在以下 TypeScript 代码中,当将参数 blobServiceClient 声明为 typeof BlobServiceClient 时,blobServiceClient 会丢失其类型并再次成为“any”类型,并且不再适用于 VSCode(自动完成)中的智能感知。但是,BlobServiceClient 仍然是正确的类型,并且可以与 VSCode 中的智能感知一起使用。

let { BlobServiceClient } = require( '@azure/storage-blob');

export class BlobStorageManager implements IBlobStorageManager {
    constructor(private blobServiceClient: typeof BlobServiceClient) {
        this.blobServiceClient = blobServiceClient;
    }
    ...
}

【问题讨论】:

    标签: typescript visual-studio-code


    【解决方案1】:

    在 typescript 中,您通常希望通过 import 关键字导入包。

    import { BlobServiceClient } from '@azure/storage-blob'
    

    它还应该获取正确的类型。 Typescript 很难确定动态 require 语句的类型。

    更改为导入似乎

    Playground with fix


    更新:

    但是,当我在另一个函数中调用this.blobServiceClient.getContainerClient(containerName) 时,this.blobServiceClient 再次属于任何类型。

    我猜你想要:

        constructor(private blobServiceClient: BlobServiceClient) {
            this.blobServiceClient = blobServiceClient;
        }
    

    请注意,typeof 已被删除。当你在 typescript 中有一个类时,该类本身被用作实例的类型,typeof SomeClass 被用作该类的构造函数的类型。

    因此,如果您希望构造函数接收BlobServiceClient 的实例,那么您应该删除typeof。

    Playground

    【讨论】:

    • 酷,适用于构造函数。但是,当我在另一个函数中调用 this.blobServiceClient.getContainerClient(containerName) 时,this.blobServiceClient 再次是 any 类型。
    • 下面的函数签名没有保留 this.blobServiceClient 的类型 -> public myFunction = async function (task: any, containerName: string) : Promise / this one do -> public async myFunction (任务:任何,容器名称:字符串):承诺
    • 查看我的答案更新。
    猜你喜欢
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 2015-09-27
    相关资源
    最近更新 更多