Last active
October 16, 2023 12:43
-
-
Save ReVoid/41704f24262a0bfdba59c4be21c492ac to your computer and use it in GitHub Desktop.
How to make an object extendable with any keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Extendable regular object | |
type Extends<T extends object> = T & Record<string, unknown>; | |
// Extendable object with extendable nested objects | |
type Extendable<T> = Extends<{ [Key in keyof T]: T[Key] extends object ? Extends<T[Key]> : T[Key] }>; | |
type Employee = { | |
name: string, | |
age: number, | |
salary: { | |
value: number, | |
currency: 'USD' | 'EUR', | |
} | |
} | |
const passenger: Extendable<Employee> = { | |
name: 'John Doe', | |
age: 30, | |
salary: { | |
value: 3500, | |
currency: 'USD', | |
whatever: 'Alien', // ✅ | |
}, | |
whatever: 'Alien: Resurrection', // ✅ | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment