Home > Software design >  Is there a way to avoid returning `any` within a JSON.parse reviver?
Is there a way to avoid returning `any` within a JSON.parse reviver?

Time:06-18

I have a project using TypeScript and ESLint. I need to deserialize a JSON string, and want to take advantage of the optional reviver parameter. A reviver function basically lets you conditionally transform values as part of the JSON deserialization.

The signature of the reviver function is defined as part of the JSON.parse specification, which is:

JSON.parse(text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined): any

In particular: it takes in a value of type any and returns a value of type any.

const deserializedValue: unknown = JSON.parse(serializedValue, (key, value) => {
  if (value === 'foo') {
    return 'bar
  }
  return value
}

I'm scolded by ESLint because when I write return value I am returning something of any type:

  5:4  error  Unsafe return of an `any` typed value  @typescript-eslint/no-unsafe-return

Is there a way for me to programmatically avoid the linting complaint about any types within the constraints of the unknown nature of deserialization, or do I have to disable the linting rule for that line?

CodePudding user response:

eslint is a bit overzealous here. Or at least that rule doesn't apply well to this case.

Parsing JSON is an inherently type unsafe process. In this case the any is just passed through from the argument type, and the function is typed in a place you can't control to return any.

So I'd probably just cast it to unknown like:

return value as unknown

Which sort of makes it clear that "I don't know or care what this is". And the return type does matter because anything matches any and the return type is used in the return type of JSON.parse().

This seems to work.

But that's probably not that much better than disabling the rule for that line either. Which is right is more a matter of opinion.

But still, I'd go with the as unknown cast.

  • Related