Skip to content

Instantly share code, notes, and snippets.

@donabrams
Last active November 8, 2018 15:29
Show Gist options
  • Save donabrams/b849927f5a0160081db913e3d52cc7b3 to your computer and use it in GitHub Desktop.
Save donabrams/b849927f5a0160081db913e3d52cc7b3 to your computer and use it in GitHub Desktop.
Typesafe omit typescript (TS 3.1.6)
// This doesn't support union types, so we have more shannanigans to do
type SimpleOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
// example union type for fun
type Before = { foo: string } | { foo: string, bar: string } | { yay: true };
type UnaryObject<K extends string | number | symbol, V> = { [P in K]: V; }
const unaryWorks: UnaryObject<'beep', string> = { beep: 'beep' };
const unaryFails1: UnaryObject<'beep', string> = { beep: true };
const unaryFails2: UnaryObject<'beep', string> = { boop: 'beep' };
type AddKey<T, K extends string | number | symbol, V> = T & { [P in K]: V };
const addKeyWorks1: AddKey<Before, 'beep', string> = { foo: 'foo', beep: 'beep' };
const addKeyWorks2: AddKey<Before, 'beep', string> = { foo: 'foo', bar: 'bar', beep: 'beep' };
const addKeyWorks3: AddKey<Before, 'beep', string> = { yay: true, beep: 'beep' };
const addKeyWorks4: AddKey<Before, 'foo', string> = { foo: 'foo' };
const addKeyWorks5: AddKey<Before, 'foo', string> = { foo: 'foo', bar: 'bar' };
const addKeyWorks6: AddKey<Before, 'foo', string> = { foo: 'foo', yay: true };
const addKeyFails1: AddKey<Before, 'beep', string> = { foo: 'foo' };
const addKeyFails2: AddKey<Before, 'beep', string> = { foo: 'foo', bar: 'bar' };
const addKeyFails3: AddKey<Before, 'beep', string> = { yay: true };
const addKeyFails4: AddKey<Before, 'foo', string> = { yay: true };
// I WANT THIS
type RemoveKey<T, K extends string | number | symbol> = ???
const removeKeyWorks1: RemoveKey<Before, 'foo'> = { };
const removeKeyWorks2: RemoveKey<Before, 'foo'> = { bar: 'bar' };
const removeKeyWorks3: RemoveKey<Before, 'foo'> = { yay: true };
const removeKeyFails1: RemoveKey<Before, 'foo'> = { foo: 'foo' };
const removeKeyFails2: RemoveKey<Before, 'foo'> = { foo: 'foo', bar: 'bar' };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment