Last active
May 23, 2020 20:40
-
-
Save KirdesMF/b27d6351a7d4965540c2098b66536d65 to your computer and use it in GitHub Desktop.
Ts Helpers
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
/**============== 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