Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any standard way in @typescript-eslint to cast a return value to 'any' without getting 'no-explicit-any' warning?

// I get @typescript-eslint of [Unexpected any. Specify a different type.eslint(@typescript-eslint/no-explicit-any)]

const funcToGetOnlineData: (url: string) => any = () => {
    // const httpData = (some processes to retrieve http request data)
    // return httpData;
};

funcToGetOnlineData('http://getsomedata.com');

Casting a return value to any is not a good practice I know. However, sometimes we indeed need this. i.e. fetching data with unknown shape via HTTP request. Without disabling the ESlint rule for these lines, is there any standard way/practice to get rid of such situation?

like image 971
mannok Avatar asked Jan 26 '26 13:01

mannok


2 Answers

maybe something like this?

interface Article {
    items: []
}

function funcToGetOnlineDataV2<T>(url: string): Promise<T> {
    return fetch(url)
        .then((response: Response) => {
            return response.json();
        });
};

funcToGetOnlineDataV2<Article>('http://getsomedata.com').then((res: Article) => {
    console.log(res);
});
like image 98
Dmitry Nizovsky Avatar answered Jan 29 '26 02:01

Dmitry Nizovsky


You cannot do so as far as I know.

However, any and unknown are top-types in TypeScript so just use unknown instead. All the values that can be assigned to any can also be assigned to unknown.

So it seems your choices are either of:

  1. Disable the linting rule for that line, or;
  2. Use unknown instead.

Trying to come up with hacks to trick the linter into thinking any isn't being used is not a good idea.

like image 27
tsujp Avatar answered Jan 29 '26 01:01

tsujp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!