05 - The Type System
📋 Jump to Takeaways🎁 Go interfaces are structural too — but TypeScript's type system can do things Go's can't, like computing new types from existing ones at compile time. What does that actually unlock?
TypeScript uses structural typing: it doesn't care about class hierarchies or implements keywords. If two types have the same shape, they're compatible. That's it. Go does this with interfaces too, but TypeScript takes it much further.
Structural Typing
interface Logger {
log(message: string): void;
}
class ConsoleLogger {
log(message: string): void {
console.log(message);
}
}
// No "implements Logger" needed. Shape matches, so it works.
const logger: Logger = new ConsoleLogger();
logger.log("hello"); // "hello"Go's ConsoleLogger would satisfy a Logger interface the same way. The difference: TypeScript checks every property and method signature deeply, not just method sets.
Basic Type Annotations
You already know static types. Here's the TypeScript syntax:
const name: string = "backend";
const port: number = 3000;
const debug: boolean = false;
// Arrays: two equivalent syntaxes
const ports: number[] = [3000, 3001, 3002];
const hosts: Array<string> = ["localhost", "0.0.0.0"];
// Tuples: fixed-length, typed at each position
const entry: [string, number] = ["localhost", 3000];
// entry[0] is string, entry[1] is number
// Tuple with labels (documentation only, no runtime effect)
type HostPort = [host: string, port: number];
const server: HostPort = ["0.0.0.0", 8080];any, unknown, and never
Three special types. They do very different things.
any turns off type checking. It's a trapdoor. Don't use it.
let data: any = "hello";
data = 42;
data = { foo: "bar" };
data.nonExistent.method(); // No error at compile time. Blows up at runtime.unknown is the safe version. You can assign anything to it, but you have to narrow the type before you touch it.
function processInput(input: unknown): string {
// input.toUpperCase(); // Error: Object is of type 'unknown'
if (typeof input === "string") {
return input.toUpperCase(); // OK, narrowed to string
}
return String(input);
}
console.log(processInput("hello")); // "HELLO"
console.log(processInput(42)); // "42"never means "this can't happen." Functions that always throw or loop forever return never.
function fail(message: string): never {
throw new Error(message);
}
// TypeScript knows code after fail() is unreachable
function getPort(env: string): number {
if (env === "prod") return 443;
if (env === "dev") return 3000;
return fail(`Unknown env: ${env}`);
}Type Narrowing
Type narrowing: TypeScript tracks types through control flow. After a check, it knows the type got more specific.
typeof
function double(value: string | number): string | number {
if (typeof value === "string") {
return value.repeat(2); // value is string here
}
return value * 2; // value is number here
}
console.log(double("ha")); // "haha"
console.log(double(21)); // 42instanceof
class HttpError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
function handleError(err: Error): string {
if (err instanceof HttpError) {
return `HTTP ${err.status}: ${err.message}`; // err is HttpError here
}
return err.message; // err is Error here
}
console.log(handleError(new HttpError(404, "Not Found"))); // "HTTP 404: Not Found"
console.log(handleError(new Error("oops"))); // "oops"The in Operator
interface DbConfig {
connectionString: string;
}
interface RedisConfig {
host: string;
port: number;
}
function connect(config: DbConfig | RedisConfig): string {
if ("connectionString" in config) {
return `Connecting to DB: ${config.connectionString}`;
}
return `Connecting to Redis: ${config.host}:${config.port}`;
}
console.log(connect({ connectionString: "postgres://localhost/mydb" }));
// "Connecting to DB: postgres://localhost/mydb"
console.log(connect({ host: "127.0.0.1", port: 6379 }));
// "Connecting to Redis: 127.0.0.1:6379"Custom Type Guards
Sometimes the built-in checks aren't enough. Write your own type guard with the is keyword.
interface ApiSuccess {
data: unknown;
error: null;
}
interface ApiError {
data: null;
error: string;
}
type ApiResponse = ApiSuccess | ApiError;
function isSuccess(res: ApiResponse): res is ApiSuccess {
return res.error === null;
}
function handleResponse(res: ApiResponse): string {
if (isSuccess(res)) {
return `Got data: ${JSON.stringify(res.data)}`; // res is ApiSuccess
}
return `Error: ${res.error}`; // res is ApiError
}
console.log(handleResponse({ data: { id: 1 }, error: null }));
// 'Got data: {"id":1}'
console.log(handleResponse({ data: null, error: "not found" }));
// "Error: not found"The return type res is ApiSuccess tells TypeScript: "if this function returns true, treat res as ApiSuccess in the calling scope."
Assertion Functions
Assertion functions narrow types by throwing if the condition fails. After the call, TypeScript knows the narrowed type.
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== "string") {
throw new Error(`Expected string, got ${typeof value}`);
}
}
function processEnv(value: unknown): string {
assertIsString(value);
// value is string from here on
return value.toUpperCase();
}
console.log(processEnv("hello")); // "HELLO"
// processEnv(42); // throws: "Expected string, got number"Same idea as Go's must pattern, but wired into the type system.
as const
as const makes values deeply readonly and narrows them to their literal types. Use it for config objects and tuples.
// Without as const
const config = { port: 3000, host: "localhost" };
// type: { port: number; host: string }
// With as const
const frozenConfig = { port: 3000, host: "localhost" } as const;
// type: { readonly port: 3000; readonly host: "localhost" }
// frozenConfig.port = 4000; // Error: Cannot assign to 'port'
// Great for tuples
const pair = [1, "hello"] as const;
// type: readonly [1, "hello"] instead of (string | number)[]
// Perfect for string literal unions from arrays
const METHODS = ["GET", "POST", "PUT", "DELETE"] as const;
type HttpMethod = (typeof METHODS)[number];
// type HttpMethod = "GET" | "POST" | "PUT" | "DELETE"Go vs TypeScript: Structural Typing Compared
Both languages use structural typing, but the depth is different.
Go checks method sets. Right methods? Satisfies the interface. Done.
TypeScript checks everything: properties, methods, nested shapes, optional fields, readonly modifiers, generic parameters. Structural typing all the way down.
interface HasLength {
length: number;
}
function printLength(item: HasLength): void {
console.log(item.length);
}
printLength("hello"); // 5 (string has .length)
printLength([1, 2, 3]); // 3 (array has .length)
printLength({ length: 42 }); // 42 (object literal matches)In Go, you'd need a method Length() int on each type. In TypeScript, a property with the right name and type is enough.
The satisfies Operator
The satisfies operator (TypeScript 4.9+) validates that a value matches a type without widening the inferred type. The difference matters when you want both type safety and precise inference.
type ServerConfig = {
port: number | string;
host: string;
};
// With a type annotation — port is widened to number | string
const config1: ServerConfig = { port: 3000, host: "localhost" };
config1.port.toFixed(2); // ❌ Error: toFixed doesn't exist on string | number
// With satisfies — TypeScript checks the shape but keeps the inferred type
const config2 = { port: 3000, host: "localhost" } satisfies ServerConfig;
config2.port.toFixed(2); // ✅ port is still inferred as numberYou'll encounter satisfies in modern TypeScript codebases where tight inference matters, like typed config objects and route definitions.
Key Takeaways
- TypeScript uses structural typing. If the shape matches, it's compatible. No explicit
implementsneeded. - Use
unknownoverany. It forces you to narrow before use, catching bugs at compile time. neverrepresents impossible states. Use it to ensure exhaustive handling.- Type narrowing happens automatically through
typeof,instanceof, andinchecks. - Custom type guards (
is) and assertion functions (asserts) let you teach TypeScript about your own narrowing logic. as constlocks values to their literal types and makes everything readonly. Use it for configs and string unions.
🎁 What if you could represent "a response is either a success with data or a failure with an error code" as a single type, and the compiler forces you to handle both cases — with no inheritance required?