Last active
January 14, 2020 22:27
-
-
Save lkster/71c41b38c5585949b7e26133c5a838f5 to your computer and use it in GitHub Desktop.
TypeScript Replace 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
type DeepReplace<T, O extends Array<any>, N extends Array<any>> = { | |
[TKey in keyof T]: Replace<T, O, N>[TKey] extends N[number] ? Replace<T, O, N>[TKey] : DeepReplace<Replace<T, O, N>[TKey], O, N>; | |
} |
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
interface ITest { | |
a: string; | |
b: number; | |
} | |
const test1: Replace<ITest, [string], [number]> = { | |
a: 5, | |
b: 6, | |
}; | |
const test2: Replace<ITest, [string, number], [boolean, string]> = { | |
a: true, | |
b: 'something', | |
} |
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
type ReplaceOrNever<T, O extends Array<any>, N extends any> = ({ | |
[OKey in keyof O]: O[OKey] extends T ? N[OKey] : never; | |
})[number]; | |
type Replace<T, O extends Array<any>, N extends Array<any>> = { | |
[TKey in keyof T]: ReplaceOrNever<T[TKey], O, N> extends never ? T[TKey] : ReplaceOrNever<T[TKey], O, N> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment