Skip to content

Instantly share code, notes, and snippets.

@KirdesMF
Last active May 23, 2020 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KirdesMF/b27d6351a7d4965540c2098b66536d65 to your computer and use it in GitHub Desktop.
Save KirdesMF/b27d6351a7d4965540c2098b66536d65 to your computer and use it in GitHub Desktop.
Ts Helpers
/**============== Avoid doing things weird with never ===========================*/
type Exact<A, B> = A extends B ? (B extends A ? A : never) : never;
// This basically says that if and A extends B and B extends A then the types are identical,
// neither are a subset or superset of the other.
// So it should allow that type through.
// If they are not identical, then the type is never which prevents that type from being allowed.
// Now you just need to make your function generic, and enforce that argument to exactly the right type:
function func<T>(param: Exact<T, LayoutType>) {
console.log(param);
}
/**************************************************/
type IFoo = {
bar: string; can?: never
} | {
bar?: never; can: number
};
let val0: IFoo = { bar: "hello" } // OK only bar
let val1: IFoo = { can: 22 } // OK only can
let val2: IFoo = { bar: "hello", can: 22 } // Error foo and can
let val3: IFoo = { } // Error neither foo or can
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment