Skip to content

Instantly share code, notes, and snippets.

@dubzzz
Created November 5, 2019 23:14
Show Gist options
  • Save dubzzz/0ecc8d6180142f580070c70375fdb7a3 to your computer and use it in GitHub Desktop.
Save dubzzz/0ecc8d6180142f580070c70375fdb7a3 to your computer and use it in GitHub Desktop.
EnableIf or enable_if in TypeScript
type EnableIf<T, U, ErrorMessage extends string = never> = T extends true ? U : ErrorMessage;
type IsArrayOf<T, U> = T extends U[] ? true : false;
function enableIf<T, U>(t: T, u: EnableIf<IsArrayOf<T, U>, U, 'T has to be an array of U'>) {
// Code
}
enableIf([1, 2], 3);
enableIf([1, 2], '3');
function enableIf2<T, U>(
t: EnableIf<T extends U ? true : false, T, 'T should be a U'>,
u: EnableIf<U extends T ? true : false, U, 'U should be a T'>) {
// Code
}
enableIf2(1, 2)
enableIf2({}, {t: 0})
enableIf2({t: 0}, {})
enableIf2({t: 0}, {t: 0})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment