Last active
February 10, 2022 12:19
-
-
Save ottokruse/1eeeaabbe2e01de7ff4bd808ff60b8ce to your computer and use it in GitHub Desktop.
TypeScript: create new type that overrides types of some fields of base type
This file contains 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
/** | |
* Let's say our base type is `Person` and we want to create a type like it, | |
* where some fields are encrypted into a Buffer instead | |
*/ | |
type Encrypted<Base, EncryptedFields extends keyof Base> = { | |
[field in keyof Base]: field extends EncryptedFields ? Buffer : Base[field]; | |
}; | |
interface Person { | |
fname: string; | |
lname: string; | |
nonencrypted: string; | |
} | |
// compiles: | |
const e: Encrypted<Person, "fname" | "lname"> = { | |
fname: Buffer.alloc(0), | |
lname: Buffer.alloc(0), | |
nonencrypted: "dddd", | |
}; | |
// Does not compile: | |
const t: Encrypted<Person, "fname"> = { | |
fname: Buffer.alloc(0), | |
lname: Buffer.alloc(0), // should be string | |
nonencrypted: "dddd", | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment