Skip to content

Instantly share code, notes, and snippets.

@FFKL
Last active March 3, 2021 20:37
Show Gist options
  • Save FFKL/d61736d79bd8b75fa81ddcc7fee21797 to your computer and use it in GitHub Desktop.
Save FFKL/d61736d79bd8b75fa81ddcc7fee21797 to your computer and use it in GitHub Desktop.
// 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