mannok
mannok

Reputation: 1851

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?

Upvotes: 4

Views: 7487

Answers (3)

tsujp
tsujp

Reputation: 1096

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.

Upvotes: 1

Shadab Faiz
Shadab Faiz

Reputation: 2508

Why not just suppress the warning like this:


  // tslint:disable-next-line: no-any
    const funcToGetOnlineData: (url: string) => any = () => {
    // const httpData = (some processes to retrieve http request data)
    // return httpData;
   };

Upvotes: -1

Dmitry Nizovsky
Dmitry Nizovsky

Reputation: 31

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);
});

Upvotes: 1

Related Questions