javascript - Hur byter man värde i typ samtidigt som man bevarar nycklar?


Jag har starttyp och typ av nycklar som bör hanteras:

import { Prisma } from "@prisma/client";

// initial type
type X = {
  a: number;
  b?: null;
  c: null;
}

type Keys = 'b' | 'c'

// final type
type Y = {
  a: number;
  b?: typeof Prisma.DbNull;
  c: typeof Prisma.DbNull;
}

                // X         // Keys      
type Generic<InitialType, KeysToHandle> = ...

Är det möjligt att få typ Y från typ X med hjälp av Generic?

Svar #1

Det du behöver kallas en Mappd-typ. Här är en typ Transform som modifierar property-typer baserat på angivna nycklar.

import { Prisma } from "@prisma/client";

type InitialType = {
  a: number;
  b?: null;
  c: null;
}

type Keys = 'b' | 'c'

type Transform<T, K extends keyof T, U = typeof Prisma.DbNull> = {
  [Key in keyof T]: Key extends K ? U : T[Key]
}

type FinalType = Transform<InitialType, Keys>