Top Bottom Types
1. Top Types
any Type
anyis the top type in TypeScript, representing any JavaScript value.anytypes are useful when the type of the variable is unknown. However, they should be avoided as much as possible.anytypes are not inherently bad; they are useful in certain cases.
let flexible: any = 1;
console.log(setTimeout, 1, "String");
unknown Type
unknownis the type-safe counterpart ofany. It represents any JavaScript value.- The difference is that you can't do anything with the
unknowntype unless you first check its type using type guards.
let myUnknown: unknown = 1;
if (typeof myUnknown === "string") {
myUnknown.toUpperCase();
} else if (typeof myUnknown === "number") {
myUnknown.toFixed();
} else {
}
Useful Use Case for unknown
- A common use case for
unknownis when catching errors. You can enforce the use ofunknowntype in the catch block using theuseUnknownInCatchVariablesTypeScript error.
function doSomething() {
if (Math.random() > 0.5) return "Ok";
else if (Math.random() > 0.5) throw "Error";
else throw new Error("Error");
}
function errorMe() {
try {
doSomething();
} catch (e: unknown) {
if (e instanceof Error) {
console.log(e.message);
} else {
console.log(e);
}
}
}
2. Object Type
- The
objecttype in TypeScript accepts all values except primitive types. - It's better to use an interface to represent an object type than the
objecttype. - The
strictNullCheckstsconfig setting will not allownullorundefinedto be assigned to anobjecttype.
let obj: object = { key: "value" };
// obj = '' Throws an error
// obj = 1 Throws an error
obj = []; // Does not throw an error
3. Bottom Types
The bottom type in TypeScript is the never type. It represents a value that never occurs. Here is an example that illustrates the never type.
class Truck {
tow() {
console.log("Towing");
}
}
class Car {
drive() {
console.log("Driving");
}
}
type Vehicle = Truck | Car;
class UnreachableaError extends Error {
constructor(val: never, message: string) {
super(message);
}
}
function moveVehicle(vehicle: Vehicle) {
if (vehicle instanceof Truck) {
vehicle.tow();
} else if (vehicle instanceof Car) {
vehicle.drive();
} else {
new UnreachableaError(vehicle, "Unknown vehicle");
}
}
4. Unit Types
The void type is used when a function does not return anything.
let myVoid: void = undefined;