Created
July 2, 2020 02:27
-
-
Save inamiy/7a3bf6ef3bba6eb8b46f1c4d7595be5f to your computer and use it in GitHub Desktop.
ReplaceProps in TypeScript
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
// 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