Last active
November 8, 2018 15:29
-
-
Save donabrams/b849927f5a0160081db913e3d52cc7b3 to your computer and use it in GitHub Desktop.
Typesafe omit typescript (TS 3.1.6)
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
// type-safe omit | |
export function omit<T extends Object, K extends string | number | symbol>(obj: T, k: K): Omit<T, K> { | |
const a = { ...(obj as Object) } as T; | |
if (k in a) { | |
delete (a as any)[k]; | |
} | |
return a as Omit<T, K>; | |
} | |
type A = { | |
foo: string, | |
bar: number, | |
}; | |
type B = { | |
foo: string, | |
beep: string | |
}; | |
type C = { | |
bar: number, | |
boop: string, | |
}; | |
type D = A | C; | |
// correctly works | |
function shouldWork(a: A): B { | |
const b: { foo: string } = omit(a, 'bar'); | |
return { | |
...b, | |
beep: a.bar.toString(), | |
}; | |
} | |
// correctly fails | |
function shouldFail1(a: A): B { | |
const b: { foo: string, bar: number } = omit(a, 'bar'); | |
return { | |
...b, | |
beep: a.bar.toString(), | |
}; | |
} | |
// correctly fails | |
function shouldFail2(a: A): B { | |
return { | |
...a, | |
beep: a.bar.toString(), | |
}; | |
} | |
// doesn't work but should :( | |
function shouldWork2(d: D): B | undefined { | |
const b: { foo: string } | { boop: string } = omit(a, 'bar'); | |
return 'foo' in b | |
? { | |
...b, | |
beep: a.bar, | |
} | |
: undefined; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment