In the world of Typescript, adding an index signature to an object can be done in a couple of different ways depending on your specific requirements. Let's imagine we have an interface called Indexable
and a type named EmployeeDir
.
type EmployeeType = "contractor" | "permanent";
type EmployeeDir = {
[key in EmployeeType]: any
}
interface Indexable {
[key: string]: any;
}
You might already know that you can create a generic function that accepts either of these two types like this:
function limited<T extends EmployeeDir | Indexable>(val: T): T {
return val;
}
However, how can you ensure that any given type actually includes an index signature? The specific structure of the index signature may vary, but the goal is to mandate its presence. How can this be achieved?
// What should be placed here to allow any type of object
// as long as it has an index signature defined?
function anything<T /* extends ...*/>(val: T): T {
return val;
}
It seems like I might be using the wrong search terms, as all my searches lead to the "object has no index signature" error, which is not quite what I'm aiming for.