Optional dynamic keys Typescript

Asked

Viewed 74 times

4

I’m trying to create an interface with dynamic keys:

type Keys = 'a' | 'b' | 'c';

interface MyInterface {
  [key: Keys]: string;
}

In doing so, I get the following error:

An index Signature Parameter type cannot be a Union type. Consider using a Mapped Object type Instead.

Using another syntax, I get a result that works, but not in the way I need:

type Keys = 'a' | 'b' | 'c';

type MyInterface = {
  [key in Keys]: string;
};

In this last way, I can use this typing in an object, but TS requests the filling of the values of all Keys, in the case a, b and c:

// Objetivo:
// Erro: Type '{ a: string; }' is missing the following properties from type 'MyInterface': b, c
const myObject: MyInterface = {
  a: 'OK',
};

// Sem erros:
const myObject: MyInterface = {
  a: 'OK',
  b: 'OK',
  c: 'OK',
};

Would have some way to make the optional keys?

Note: I am not using [key: string]: string because I want the "Intellisense" show the fields available for filling.

1 answer

6


You can declare optional properties using the question sign:

type Keys = 'a' | 'b' | 'c';

type MyInterface = {
  [key in Keys]?: string;
};

Another option is to use the built-in type Partial<T>, which makes all T-type properties optional:

type Keys = 'a' | 'b' | 'c';

type MyInterface = Partial<{
  [key in Keys]: string;
}>;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.