Reputation: 33
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?
Upvotes: 3
Views: 431
Reputation: 249676
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.
Upvotes: 1