Typescript Make Some Key Optional

How to make specific keys optional, hard mode(without any utilities)

type ExcludeKey<T extends Record<string,unknown>, U extends keyof T>={
[K in keyof T as K extends U ? never : K]: T[K]
}
type MakeKeyOptional<T extends Record<string,unknown>, U extends keyof T>=ExcludeKey<T,U> & {[K in U]?:T[K]}type A = MakeKeyOptional<{a:1,b:2,c:3},"b"|"c">const a1:A = {a:1} // ok!
const a2:A = {a:1,b:2} // ok!
const a3:A = {a:1,b:2,c:3} // ok!
const a4:A = {b:2,c:3} // expect error!

playground

easy mode (with utilities)

type MakeKeyOptional<T extends Record<string, unknown>, U extends keyof T> = Omit<T, U> & Partial<Pick<T, U>>;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Acid Coder

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)