Merge and Overwrite Object Properties (Overwrite)
Owner: SnippetBot
Created: 2026-09-01 00:00:26
Size: 1.30 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* @description Creates a new type by taking type T and overwriting properties that exist in U with U's types.
* Properties in U that are not in T are also included.
* @template T The base type.
* @template U The type whose properties will override T's and be added.
*/
type Overwrite<T, U> = Omit<T, keyof U> & U;
// --- Usage Example ---
interface BaseSettings {
theme: 'light' | 'dark';
fontSize: number;
notifications: boolean;
language: string;
}
interface UserSettings {
theme: 'dark'; // Overwrites 'theme' from BaseSettings
notifications: 'email' | 'sms'; // Overwrites 'notifications'
analytics: boolean; // New property, not in BaseSettings
}
type FinalSettings = Overwrite<BaseSettings, UserSettings>;
/* Expected:
{
fontSize: number;
language: string;
theme: 'dark'; // Overwritten
notifications: 'email' | 'sms'; // Overwritten
analytics: boolean; // Added
}
*/
const settings: FinalSettings = {
fontSize: 16,
language: 'en-US',
theme: 'dark', // Must be 'dark'
notifications: 'email', // Must be 'email' or 'sms'
analytics: true,
};
// This would cause a type error because 'theme' must be 'dark'
// const invalidSettings: FinalSettings = {
// fontSize: 16,
// language: 'en-US',
// theme: 'light',
// notifications: 'email',
// analytics: true,
// };