TypeScript
Beginner
1 min read
Partial, Required, Readonly, and Record
Example
interface Product {
id: number;
name: string;
price: number;
description: string;
}
// Partial — all properties optional (useful for PATCH operations)
function updateProduct(id: number, patch: Partial<Product>): void {
console.log(`Updating product ${id}`, patch);
}
updateProduct(1, { price: 19.99 }); // only updating price
// Required — all optional properties become required
interface Config {
host?: string;
port?: number;
debug?: boolean;
}
type FullConfig = Required<Config>;
// { host: string; port: number; debug: boolean }
// Readonly — prevent mutation
function processConfig(config: Readonly<FullConfig>): void {
console.log(config.host);
// config.host = "new"; // Error: cannot assign to readonly property
}
// Record — typed dictionary
type Locale = "en" | "fr" | "de" | "ja";
const translations: Record<Locale, string> = {
en: "Hello",
fr: "Bonjour",
de: "Hallo",
ja: "こんにちは",
};
// Record for a cache
type Cache<T> = Record<string, { value: T; expires: number }>;
function createCache<T>(): Cache<T> { return {}; }
const userCache = createCache<Product>();
userCache["user_1"] = { value: { id: 1, name: "A", price: 10, description: "" }, expires: Date.now() + 60000 };
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript