I have a query regarding a potential design gap in TypeScript. Consider a function that accepts objects meeting a specific interface:
interface Params {
[key: string]: string | number | boolean | undefined | null;
}
This interface specifies that the keys must be strings and the properties can be primitive types or void.
If I define another method that takes an interface fulfilling the Params interface, I encounter an error stating that the other interface lacks an index signature. An example of such an interface could be:
interface Foo {
bar: string;
}
Even changing the signature to
Record<string, string | number | boolean | undefined | null>
does not resolve the missing index signature issue.
A snippet of code demonstrating this scenario is shown below. It is essential to specify the key and value type of the object for certain operations with Object.entries
:
function specificFunction(obj: Foo) {
genericFunction(obj);
}
function genericFunction(params: Params) {
Object.entries(params).forEach(([key, value]) => {
…
})
}
EDIT: It is crucial that the behavior of the specificFunction remains unchanged, as it serves to narrow down the allowed interface. This restriction ensures specific properties are present in objects to achieve a desired outcome.