Skip to content

Instantly share code, notes, and snippets.

@ottokruse
Last active February 10, 2022 12:19
Show Gist options
  • Save ottokruse/1eeeaabbe2e01de7ff4bd808ff60b8ce to your computer and use it in GitHub Desktop.
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
/**
* 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