DEV Community

Morokhovskyi Roman
Morokhovskyi Roman

Posted on

3 2

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay