DEV Community

Morokhovskyi Roman
Morokhovskyi Roman

Posted on

TypeScript any or unknown?

What is the difference between 'unknown' and 'any' in TypeScript?

'unknown' is more type-safe and contributes to TypeScript control flow-based type analysis. This means you can't assign 'unknown' type to any other variable type without type checking.

Here example with unknown

function testFunc(nameOfVar: unknown) { 
    if (typeof nameOfVar == 'string') {
        const anotherStringVar: string = nameOfVar;
    }
}
Enter fullscreen mode Exit fullscreen mode

Example with any

function testFunc(nameOfVar: any) { 
    const anotherStringVar: string = nameOfVar;
}
Enter fullscreen mode Exit fullscreen mode

'Any' type literally could be assigned to any value.

When you should use 'unknown'?

'unknown' requires your code to be more predictable. Because you clearly assign a value if a type is definitely correct.
unknown is recommended because it provides safer typing — you have to use type assertion or narrow it to a specific type.

Can I use 'any' instead of 'unknown'?

Yes, you can but then TypeScript won't control strictly your assignments. This is a bit risky because your code can't guarantee that called or assigned variable has the correct type.

I Hope, I brought you some useful content.

Follow me on 🐦 Twitter if you want to see more content.

Top comments (0)