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.