interview community logo

1
0
What's the difference between any and unknown in TypeScript
1 answer

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

TypeScript Robert Isaac asked 11 months ago


0

while anything be assigned to both any and unknown

the difference is you can't assign unknown to anything other than another unknown or any

but for any, you can assign it to anything

simple example for assigning anything to any and unknown, all of these will not throw error

let u: unknown;
u = 'string';
u = 1;
u = true;
u = [];
u = {};

let a: any;
a = 'string';
a = 1;
a = true;
a = [];
a = {};

let's see assigning any to other variables

let a: any;
const s: string = a;
const n: number = a;
const b: boolean = a;
const array: number[] = a;

all of these works fine

now let's check for unknown

let u: unknown;
const s: string = u;
const n: number = u;
const b: boolean = u;
const array: number[] = u;

all of them will throw an error TS2322: Type 'unknown' is not assignable to type 'string'. where string will be changed according to the variable type

but these will work

let u: unknown;
const u2: unknown = u;
const a: any = u;

how to use unknown?

you need to narrow down the type to use it, here is example

let u: unknown;
if (typeof u === 'string') {
  const s: string = u;
}

if (typeof u === 'number') {
  const n: number = u;
}

if (typeof u === 'boolean') {
  const n: boolean = u;
}

if (Array.isArray(u)) {
  const array: number[] = u;
}

when should I use any and when to use unknown?

you should avoid using any, as it can lead to errors to the code

use unknown if the variable or function input is unknown for you, this will give you high type safety in your code without limiting the useability of it

Robert Isaac answered 11 months ago loading comments...