0

I remember reading in the docs that all types are assignable to any. But I don't remember reading that any was assignable to every other type.

function takesAString(x: string) {
    console.log(x);
}

const xAny: any = {}

takesAString(xAny);   // <--- WHY IS THIS NOT AN ERROR ?
takesAString(true);
takesAString(111);

enter image description here

I ran into this trouble in a try-catch loop:

catch(err) {                    // TYPESCRIPT EVALUATES err AS any
  dispatch(SOME_ACTION(err));   // THIS EXPECTS err TO BE OF TYPE STRING
}

Typescript implicitly evaluates catch block err argument as any, and does not give me any heads up that SOME_ACTION(err) might not be getting a string as it was intended.

Is this normal behavior? How to deal with this?

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336
  • Yes, `any` is assignable to anything. If that's not what you want, that's why `unknown` was introduced, see e.g. https://stackoverflow.com/questions/51439843/unknown-vs-any. – jonrsharpe Oct 01 '20 at 16:29

2 Answers2

1

It's not an error because any specifically opts out of type checking. From the documentation:

Any

In some situations, not all type information is available or its declaration would take an inappropriate amount of effort. These may occur for values from code that has been written without TypeScript or a 3rd party library. In these cases, we might want to opt-out of type checking. To do so, we label these values with the any type ...

(my emphasis)

Contrast this with the unknown type (which I think is relatively new), where the line you flagged in your code is indeed an error:

const xUnknown: unknown = {}

takesAString(xUnknown);   // <--- This is an error

Playground link

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You want to use the new feature to label catch variable as unknown

try {
  // ...
}catch(err: unknown) {   // no longer typed as any
  dispatch(SOME_ACTION(err));   // this is correctly error now.
}
Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59