3

Currently we are migrating our codebase to typescript and we have many places with any type. So I am trying to enforce explicit setting variables as any.

Here is example snippet.

const a: string = 'h';
const b: any = 4;

const message = a || b; 
// Here I would like to get warning that I am assigning any to the message,
// so I would have to write const message: any = a || b;

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

say(message);

I am aware about the tslint rule typedef (It requires to typedef all variables and not only in cases of any), also no-unsafe-any (doesn't work in this case).

Is there a way to require explicitly define any type if you are trying to assign any to it?

  • 2
    There is also a rule `no-any` for tslint i believe. Other than that no, there is no way to get a warning. Use `unknown` instead and void `any` at all cost – Titian Cernicova-Dragomir Aug 07 '19 at 11:01
  • Thank you very much. Unknown is exactly what was needed. I will add tslint no-any rule and ignore all current any, so we could rewrite them to unknown or type def them as time goes. – Gytis Vinclovas Aug 07 '19 at 11:47

1 Answers1

1

Ideally you should avoid any. any is by definition assignable to anything and from anything. It is mean to be unsafe and it also has the unfortunate habit of spreading.

You can use the safer unknown type. This is similar to any in that you can assign anything to it and is meant to represent data for which you don't have a well defined type. Unlike any however you can't do anything with it without a type assertion or type guard. See any vs unknown

Other that that enable the tslint no-any to stop everyone from using any and take care with predefined functions such as JSON.parse which may still sneak in an any now and then.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357