Search code examples
typescripttypescript-types

allowed explicit any type global variable used as non-any type function's returned value


this code compiles in typescript:

let varTest: any;

const funcTest: () => number = () => {
    return varTest;
};

why is that? What's the logics behind this?


Solution

  • Because TypeScript compiler ignores type checking for any. That means any is a valid type for all the types in typescript. For example,

    let a: number = 0;
    let b: any = "this is string";
    
    a = b;
    

    The above code compiles WITHOUT an error because TypeScript sees that the type of b is any so it can be assigned to a variable with any (string, number, boolean, etc...) type of value.