Below is an example of code to consider:
interface MyInterface {
foo: string
bar: string
baz: string
}
const myObj: MyInterface = {
foo: "foo",
bar: "bar",
baz: "baz"
};
Object.keys(myObj).forEach(obj => {
obj = myObj[obj];
});
When strict mode is enabled, the error TS7017 occurs: Element implicitly has an 'any' type because type 'MyInterface' has no index signature.
An easy fix would be:
interface MyInterface {
[key: string]: string;
foo: string
bar: string
baz: string
}
However, this approach allows for any string properties in MyInterface-objects.
Another consideration would be to use a mapped type:
type ValidEnteries = "foo" | "bar" | "baz";
type Alternative = {
[key in ValidEnteries]: string
}
While this solution might seem correct, it brings back the original problem of missing an index signature.
Is there a way to include an index signature while also restricting the number of properties in an object?