Any, unknown & Type Casting
Any
- TypeScript will not check the type of this variable
- This is useful when you don't know the type of a variable, or when you want to avoid type checking
let a: any = 42;
a = "hello";
Unknown
- Similar to any, but you cannot access any properties of an unknown type, nor can you call/construct them.
let b: unknown = 42;
b = "hello";
frontEndMastersFounding
type is date because value is date.date1
type is date because value is date.date2
type is any because of type casting.
let frontEndMastersFounding = new Date("Jan 1, 2012")
let date1 = frontEndMastersFounding
let date2 = frontEndMastersFounding as any;
const humid3 = 79 as number; //✔️ is 79 a number? If so, this is safe!
date3
type is date because of type casting. But value is string. So, it will throw error.- To solve the throw error, we can use
as any
top us to avoid type checking.
let date3 = "oops" as any as Date //! TypeScript thinks this is a Date now, but it's really a string
date3.toISOString() //! what do we think will happen when we run this? 💥