Title: Explicitly assign any type in typescript
Tags: typescript;any;explicit
Question: 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?
Comment: 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.

Comment: 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

Here is the accepted answer: 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.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2019:00:08/07/19', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<typescript><any><explicit>', 'Title': 'Explicitly assign any type in typescript', 'ViewCount': 241, 'id': 57392881, 'user_AboutMe': None, 'user_AccountId': 13686913.0, 'user_DisplayName': 'Gytis Vinclovas', 'user_Reputation': 33.0, 'user_Views': 1.0, 'user_id': 9875784.0}}