How to create Record with dynamic string union property names that are optional?

711 Views Asked by At

I want to define an object type where the property names are pre-defined, but also optional.

I want to create the equivalent of the below longer syntax, but is there a way to make it dynamic with optional properties so I could easily add / remove those options?

interface List {
  one?: string;
  two?: string;
  three?: string;
}

I'm trying to find a way to make the following invalid code work.

type options = 'one' | 'two' | 'three';
type List = Record<options, string>;

// Valid
const MyObjOne: List = {
    one: 'Value 1',
    two: 'Value 2',
    three: 'Value 3',
}

// Invalid
const MyObjTwo: List = {
  one: 'Value 1',
  two: 'Value 2',
}

But TypeScript gives this error for MyObj TS Playground link

Property 'three' is missing in type '{ one: string; two: string; }' but required in type 'List'.

1

There are 1 best solutions below

0
pzaenger On BEST ANSWER

Use the utility type Partial:

type List = Partial<Record<options, string>>;