Skip to content

Instantly share code, notes, and snippets.

@inamiy
Created July 2, 2020 02:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inamiy/7a3bf6ef3bba6eb8b46f1c4d7595be5f to your computer and use it in GitHub Desktop.
Save inamiy/7a3bf6ef3bba6eb8b46f1c4d7595be5f to your computer and use it in GitHub Desktop.
ReplaceProps in TypeScript
// https://stackoverflow.com/questions/53011500/how-to-replace-properties-using-mapped-types-in-typescript
// https://twitter.com/inamiy/status/1278511811025711104
type ReplaceProps<T, From, To> = {
[K in keyof T]: K extends keyof From
? T[K] extends From[K]
? K extends keyof To
? To[K]
: T[K]
: T[K]
: T[K]
}
interface From {
foo: string
bar?: boolean
baz: () => number
}
interface To {
foo(x: number): boolean
bar(): void
baz: string
}
interface Input {
foo?: string // matches `From`
bar: boolean // matches `From`
baz: number // doesn't match `From`
aNumber: number
aMethod(): void
}
type Output = ReplaceProps<Input, From, To>
// type Output = {
// foo?: (x: number) => boolean;
// bar: () => void;
// baz: number;
// aNumber: number;
// aMethod: () => void;
// }
type ReplacePropsSimple<T, To> = {
[K in keyof T]: K extends keyof To ? To[K] : T[K]
}
type Output2 = ReplacePropsSimple<Input, To>
// type Output2 = {
// foo?: (x: number) => boolean;
// bar: () => void;
// baz: string;
// aNumber: number;
// aMethod: () => void;
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment