DEV Community

Cover image for Type Safety in TypeScript - Unknown vs Any

Type Safety in TypeScript - Unknown vs Any

Sachin Chaurasiya on March 11, 2024

TypeScript is very popular because it adds static typing to JavaScript. This makes the code safer and better quality, which JavaScript developers l...
Collapse
 
ketav_chotaliya profile image
Ketav Chotaliya • Edited

In simpler terms,

any lets you do anything you want
unknown doesn't let you do anything at all without checking the type first.

let vAny: any = 10; // We can assign anything to any
let vUnknown: unknown = 10; // We can assign anything to unknown just like any

let s1: string = vAny; // Any is assignable to anything
let s2: string = vUnknown; // Invalid; we can't assign vUnknown to any other type (without an explicit assertion)

Collapse
 
martygo profile image
Martins Gouveia

Thanks for sharing this insight. 👌 It’s really helpful.

Collapse
 
sachinchaurasiya profile image
Sachin Chaurasiya

Thanks for reading and glad you find it helpful.

Collapse
 
cheikhnouha profile image
Cheikhnouha

GOOD STOTY

Collapse
 
cheikhnouha profile image
Cheikhnouha

GOOD STOTY

Collapse
 
_ndeyefatoudiop profile image
Ndeye Fatou Diop

Thanks for sharing this. Any is especially bad because if the conditions change, you won’t get any warning

Collapse
 
sachinchaurasiya profile image
Sachin Chaurasiya

Exactly, thanks for reading.

Collapse
 
pratiknashikkar profile image
CodePrati

Really helpful insight. 👍

Collapse
 
sachinchaurasiya profile image
Sachin Chaurasiya

Glad you find it helpful.

Collapse
 
jangelodev profile image
João Angelo

Hi Sachin Chaurasiya,
Your tips are very useful
Thanks for sharing

Collapse
 
sachinchaurasiya profile image
Sachin Chaurasiya

Glad you find it useful.