vitaly-t
vitaly-t

Reputation: 25840

TypeScript + WebStorm unwanted typeof warnings

What is the recommended approach today to dealing with TypeScript unwanted checks that pertain to use from JavaScript?

I have the following function:

function connect(config: string): void {

    // Getting warning for the line that follows:
    //     typeof check is always false: 'config' always has type 'string'

    if (typeof config !== 'string') {
        throw new Error('Connection config must be a string');
    }

    // execute normally...
}

I am using WebStorm UI, which pops up such warnings in a few places. The warning is irrelevant, because the module is compiled into JavaScript, and distributed as such, so the verification is strictly for calls from JavaScript clients. But there can also be TypeScript clients, so I cannot just change the function parameter type to any in the declaration.

What is the modern and recommended approach to getting rid of such warnings? Preferably, not in a way that disables such checks completely.

Upvotes: 2

Views: 366

Answers (2)

vitaly-t
vitaly-t

Reputation: 25840

After trying some suggestions here, I found it to be the easiest to do inline re-cast into any:

function connect(config: string): void {
    if (typeof config as any !== 'string') {
        throw new Error('Connection config must be a string');
    }
}

That way, any TypeScript client will be correctly required to pass in a string, while any JavaScript client will get an error thrown, if it passes in anything other than a string.

And we are no longer getting any of those typeof warnings.

Upvotes: 1

Akash
Akash

Reputation: 4553

You don't need check for the type of config since the compiler will throw error wherever you try to pass a non string config value to the function. ie, the check has to happen before the function call.

OR

If the config can be of any type and need to be checked, you need to define the function as follows

function connect(config: any)

As per your code the type of your config is always a string. So, the compiler error makes sense.

Upvotes: 0

Related Questions