TypeScript Unknown Type

unknown type means that the type of variable is not known. It is the type-safe counterpart of any. We can assign anything to an unknown variable, but the unknown isn’t assignable to any other types except to unknown and any. To use an unknown type, we need to first assert its type or narrow it to a more specific type.

Unknown Type

Unknown type is a top type in TypeScript. You can assign anything to an unknown type.

let unknownVar:unknown;

unknownVar = true;                   //boolean 
unknownVar = 10;                     //number
unknownVar = 10n;                    //BigInt  >>=ES2020
unknownVar = "Hello World";             //String
unknownVar = ["1","2","3","4"]              //Array                
unknownVar = {firstName:'', lastName:''}; // Object
unknownVar = null;                  // null
unknownVar = undefined;             // undefined
unknownVar = Symbol("key");        // Symbol

You can assign unknown to a variable of type unknown and any.

let value: unknown;

let value1:unknown = value; // OK
let value2:any = value;     // OK

But cannot assign unknown to any other types.

let value: unknown;

let value1: boolean = value;  // Error
let value2: number = value;   // Error
let value3: string = value;   // Error
let value4: object = value;   // Error
let value5: any[] = value;    // Error
let value6: Function = value; // Error

Type Assertion

You can use the Type Assertion on an unknown type to let the compiler know the correct type.

let value: unknown;

let value1: boolean = value as boolean;   // OK
let value2: number = value as number;     // OK
let value3: string = value as string;     // OK
let value4: object = value as object;     // OK
let value5: any[] = value as any;         // OK
let value6: Function = value as Function; // OK

Narrowing the unknown Type

Another way is to narrow the types using type guards.

let value: unknown;

if (typeof value =="boolean") {
    let value1: boolean = value;   // OK
}
if (typeof value =="number") {
    let value1: number = value;   // OK
}
if (typeof value =="string") {
    let value1: string = value;   // OK
}

Unknown Vs Any

Both Any & Unknown data types are used when we do not know the Type.

Any Type

  1. You can assign anything to any type 
  2. You can perform any operation on any type

For Example, the following code does not throw any compiler errors. But this will result in run time errors. This is one of the major issues with using any type. This is why you should avoid using Any.

let anyVar: any;

anyVar.someMethod()
anyVar[0]
new anyVar();

Unknown Type

  1. You can assign anything to unknown type
  2. You cannot perfom any operation on unknown type unless you perform a type check or type assertion

The above code with unknown type results in compiler error (Object is of type 'unknown'.).

let anyVar: unknown;

anyVar.someMethod()       //Object is of type 'unknown'
anyVar[0]
new anyVar();

The following code with the Any type does compile, but with Unknown type throws compile error.

function addNum(num1: unknown, num2:unknown) {
    return num1+num2  ;      //Object is of type 'unknown'.
}
 
addNum(1,1)

You need to use the Typeof type guard to narrow the type to number to make it work without any issue. With this approach, you are sure not to get any run time errors. This is why the unknown type is recommended over Any type.

function addNum(num1: unknown, num2:unknown) {
    if (typeof num1=="number" && typeof num2 == "number") {
        return num1+num2  ;
    }
    return 0
}
 
addNum(1,1)

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top