Home > database >  TS typeof in constructor parameter loses type and VSCode auto-complete
TS typeof in constructor parameter loses type and VSCode auto-complete

Time:10-06

In the following TypeScript code when declaring the parameter blobServiceClient as typeof BlobServiceClient, blobServiceClient loses its type and is again of type "any" and no longer works with intellisense in VSCode (auto-complete). BlobServiceClient however is still of the correct type and works with intellisense in VSCode.

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

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

CodePudding user response:

In typescript you typically want to import packages via the import keyword.

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

Which should also fetch the right types along with it. Typescript has a harder time with figuring out the types of dynamic require statements.

Change that to import seems to

Playground with fix


Update:

However, when I call this.blobServiceClient.getContainerClient(containerName) in another function this.blobServiceClient is again of type any.

I'm guessing you want:

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

Note that the typeof was removed. When you have a class in typescript, the class itself is used as the type of instances, and typeof SomeClass is used for the type of the constructor of that class.

So if you are expecting the constructor to receive an instance of BlobServiceClient then you should remove the typeof.

Playground

  • Related