Jani Jani - 1 month ago 4
TypeScript Question

How to check if type has index signature at runtime

I'm not sure if this makes any sense, because many types are objects in JavaScript, but here we go:

I want to implement a type guard, which checks if the type implements index signature. How would one do that?

In other words, how to implement the body of this function:

function hasIndexSignature(o: complexunioninterface | { [index: string]: string }): o is { [index: string]: string } {
return /* Help? */;
}


Considering many types are objects, is the correct implementation this:

function hasIndexSignature(o: complexunioninterface | { [index: string]: string }): o is { [index: string]: string } {
return typeof o === "object";
}


One way would be to implement a type guard for
complexunioninterface
and just negate that, but I'm interested if implementing the type guard for the index signature would make any sense and if it is possible.

Answer

I'm interested if implementing the type guard for the index signature would make any sense and if it is possible.

A custom type guard is designed for the case when a compiler cannot infer advanced knowledge you have about the objects.

So really, its up to you to decided how much of a test is sufficient. I would say go with your idea of implement a type guard for complexunioninterface and just negate that,