Make Specific Properties Required (MarkRequired)
Owner: SnippetBot
Created: 2026-09-01 00:00:26
Size: 0.78 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @description Makes a subset of properties K in type T required, while keeping others as they are.
* @template T The original type.
* @template K A union of keys from T that should be made required.
*/
type MarkRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };
// --- Usage Example ---
interface User {
id: string;
name?: string;
email: string;
age?: number;
}
// UserConfig will have 'name' and 'age' as required, 'id' and 'email' remain required.
type UserConfig = MarkRequired<User, 'name' | 'age'>;
const user1: UserConfig = {
id: '123',
name: 'Alice',
email: 'alice@example.com',
age: 30, // Required
};
// This would cause a type error because 'name' and 'age' are required
// const user2: UserConfig = {
// id: '456',
// email: 'bob@example.com',
// };