Skip to content

Instantly share code, notes, and snippets.

@BiosBoy
Created August 8, 2024 06:25
Show Gist options
  • Save BiosBoy/c3db116c7ed8fa0e3d3e77dfcfee8b7c to your computer and use it in GitHub Desktop.
Save BiosBoy/c3db116c7ed8fa0e3d3e77dfcfee8b7c to your computer and use it in GitHub Desktop.
interface User {
id: number;
name: string;
email: string;
}
function updateUser(userId: number, updates: Partial<User>) {
// Imagine this function updates a user in the database
console.log(userId, updates);
}
updateUser(1, { name: 'Alice' }); // Works perfectly, 'email' is optional
interface Config {
host?: string;
port?: number;
}
function initializeServer(config: Required<Config>) {
console.log(`Starting server at ${config.host}:${config.port}`);
}
initializeServer({ host: 'localhost', port: 8080 }); // Works fine
initializeServer({ host: 'localhost' }); // Error: Property 'port' is missing
interface Point {
x: number;
y: number;
}
const point: Readonly<Point> = { x: 1, y: 2 };
point.x = 5; // Error: Cannot assign to 'x' because it is a read-only property
type Status = 'pending' | 'completed' | 'failed';
const statusMessages: Record<Status, string> = {
pending: 'The task is pending',
completed: 'The task has been completed',
failed: 'The task has failed',
};
console.log(statusMessages.pending); // 'The task is pending'
interface User {
id: number;
name: string;
email: string;
}
type UserSummary = Pick<User, 'id' | 'name'>;
const userSummary: UserSummary = {
id: 1,
name: 'Alice',
};
console.log(userSummary);
interface User {
id: number;
name: string;
email: string;
}
type UserWithoutEmail = Omit<User, 'email'>;
const user: UserWithoutEmail = {
id: 1,
name: 'Bob',
};
console.log(user);
type Status = 'pending' | 'completed' | 'failed';
type NonFailedStatus = Exclude<Status, 'failed'>;
const status: NonFailedStatus = 'completed'; // Works
const anotherStatus: NonFailedStatus = 'failed'; // Error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment