...

Web Technologies - TypeScript

Back to Course

Lesson Description


Lession - #1443 TypeScript Special Types


TypeScript has special types that may not relate to any specific type of data.

Type any
any is a type that disables type checking and effectively allows all types to be used.

The illustration below doesn't use any and will throw an error

illustration without any


let u = true;
u = " string";// Error Type' string' isn't assignable to type' boolean'.
( u>
;// Error Argument of type' boolean' isn't assignable to parameter of type' number'.


Setting any to the special type any disables type checking

illustration with any

let v any = true;
v = " string";// no error as it can be" any" type
( v>
;// no error as it can be" any" type


any can be a useful way to get once errors since it disables type checking, but TypeScript won't be suitable give type safety, and tools which calculate on type data, similar as auto completion, won't work. Remember, it should be avoided at" any" cost.

Type unknown
unknown is a similar, but safer alternative to any.

TypeScript will help unknown types from being used, as shown in the below illustration


let w unknown = 1;
w = " string";// no error
w = {
runANonExistentMethod(>
= >{ (" I suppose thus I am">
; as{ runANonExistentMethod(>
= > void} / How can we avoid the error for the code commented out below when we do not know the type? /w.runANonExistentMethod(>
;// Error Object is of type' unknown'. if( typeof w === ' object' & & w! == null>
{ w as{ runANonExistentMethod Function}>
. runANonExistentMethod(>
;


/ Although we've to cast multiple times we can do a check in the if to secure our type and have a safer casting

Compare the illustration above to the previous illustration, with any.

unknown is best used when you do not know the type of data being typed. To add a type later, you will need to cast it.

Casting is when we use the" as" keyword to say property or variable is of the casted type.

Type never
never effectively throws an error whenever it's defined.


let x noway = true;// Error Type' boolean' isn't assignable to type' never'.


noway is rarely used, especially by itself, its primary use is in advanced generics.

Type undefined & null
undefined and null are types that relate to the JavaScript primitives undetermined and null respectively.


let y undefined = undefined;
let z null = null;