Last active
March 3, 2021 20:37
-
-
Save FFKL/d61736d79bd8b75fa81ddcc7fee21797 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// T and E extends checking should be array for primitives support | |
// See https://mariusschulz.com/blog/conditional-types-in-typescript#distributive-conditional-types | |
type Exact<T, E> = T[] extends E[] | |
? E[] extends T[] | |
? T | |
: never | |
: never; | |
// Primitives | |
declare function exactStringOrBoolean<T>(input: Exact<T, string | boolean>): void; | |
declare function stringOrBoolean(input: string | boolean): void; | |
const value = 'string'; | |
exactStringOrBoolean(value); // Error! | |
stringOrBoolean(value); | |
// Object Types | |
type User = { | |
name: string, | |
surname: string, | |
} | |
declare function safeUserOnly<T>(input: Exact<T, User>): void; | |
declare function userOnly(input: User): void; | |
const user = { name: 'John', surname: 'Doe', city: 'New York' }; | |
safeUserOnly(user); // Error! | |
userOnly(user) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment