'Define incomplete Record, while retaining the constraints on mapped type

Say I have an interface S:

interface S {
  a: string;
  b: number;
  c: string;
}

I want to create an incomplete mapping from S to some other AllowedMappedType type:

type AllowedMappedType = "red" | "green" | "blue";
const map: Record<keyof S, AllowedMappedType> = {
  a: "red",
  c: "green",
};

This doesn't work, because we don't define a mapping for all keys of S. You could avoid this by getting rid of type specialization:

const map = {
  a: "red",
  c: "green",
}; // map has a type of { a: string, c: string }, i.e. we lose the constraint on AllowedMappedType

But I want to retain the AllowedMappedType constraint. Partial doesn't work for me either because I want the type to not have optional properties.

How to achieve this?



Solution 1:[1]

How about Pick?

interface S {
    a: string;
    b: number;
    c: string;
  }
type AllowedMappedType = "red" | "green" | "blue";
const map: Pick<Record<keyof S, AllowedMappedType>, 'a' | 'c'> = {
  a: "red",
  c: "green",
};

Or Omit:

const map: Omit<Record<keyof S, AllowedMappedType>, 'b'> = {
    a: "red",
    c: "green",
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Patrick Mascari