DEV Community

Acid Coder
Acid Coder

Posted on • Edited on

4 3

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!
Enter fullscreen mode Exit fullscreen mode

playground

easy mode (with utilities)

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay