Lesser-Known TypeScript Types
TypeScript is now the default in many teams. Types act as documentation and safety nets. Still, some types aren’t used often—I didn’t truly understand them until I dug deeper. Here are a few worth noting.
never
Key points:
never
is the bottom type.- It’s useful in exhaustive checks to ensure new cases aren’t forgotten.
void
means a function returnsundefined
;never
means it never returns.
Example:
interface Circle {
kind: 'circle';
radius: number;
}
interface Square {
kind: 'square';
sideLength: number;
}
type Shape = Circle | Square;
function getArea(shape: Shape) {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.sideLength ** 2;
default:
const exhaustiveCheck: never = shape;
return exhaustiveCheck;
}
}
If you later add Triangle
to Shape
, the assignment to never
fails, reminding you to update the switch.
Further reading:
- https://stackoverflow.com/questions/40251524/typescript-never-type-inference
- https://en.wikipedia.org/wiki/Bottom_type
- https://fullstackbb.com/typescript/never-type-in-typescript/
ArrayLike
, PromiseLike
TypeScript’s lib definitions include “like” types. ArrayLike<T>
differs from Array<T>
:
interface ArrayLike<T> {
readonly length: number;
readonly [n: number]: T;
}
interface Array<T> {
length: number;
toString(): string;
pop(): T | undefined;
// ...
}
ArrayLike
only requires an indexed collection with a length. Array
has full methods like pop
.
Example:
function getSize(arr: ArrayLike<any>): number {
return arr.length;
}
console.log(getSize([1, 2, 3])); // ok
function fn() {
console.log(getSize(arguments)); // ok with ArrayLike; would fail with Array
}
Useful for arguments
or DOM collections that aren’t real arrays.
More info: https://stackoverflow.com/questions/43712705/why-does-typescript-use-like-types
Closing Thoughts
If you only ever use interface
, Pick
, Omit
, and unions, you’re missing a lot of TypeScript’s power. Learn these niche types to write more expressive, safer code.