QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Keys to Optional

Makes only the specified keys of an object type optional.

  • helper-types
  • typedefinition
  • optional

Install

npx shadcn@latest add https://quicksnip.dev/r/keys-to-optional.json

This snippet is not verified yet. Review it before use, or help verify it.

Code

type OptionalKeys<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

Usage

type A = {
    id: string;
    name: string;
    age: number;
};

type WithOptionalName = OptionalKeys<A, "name">;
// { id: string; age: number; name?: string }

type WithOptionalNameAndAge = OptionalKeys<A, "name" | "age">;
// Result: { id: string; name?: string; age?: number }