Typescript: Strict Checks Against "Any"

Viewed 1289

My Typescript configuration is allowing the following code to compile:

const thing : any = 123
const name : string = thing

Clearly, name is not actually a string, but the fact that I declare it as any makes my typechecker ignore it.


How can I configure my tsconfig.json to give me an error until I provide the correct types for my object?

My current configuration:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noEmitOnError": true,
        "noImplicitAny": true,
        "noImplicitReturns": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "strictNullChecks": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist",
        "baseUrl": ".",
        "paths": {
            "*": [
                "node_modules/*",
                "src/types/*"
            ]
        }
    },
    "include": [
        "src/**/*.ts"

    ]
}
2 Answers

The type any disables the type checker by design. As of TypeScript 3.0, there is another type called unknown which is basically a strict version of any.

const thing: unknown = 123;
const name: string = thing; // <- error TS2322: Type 'unknown' is not assignable to type 'string'.

You can find more about it in the release notes of TypeScript 3.0. For now – about two years after release –, the type is not yet listed as one of the basic types on the website. However, there is a beta for a new version of the website which also lists unknown.

Related