Typescript assign 'Object' a specific type instead of 'any'

Viewed 208

Because of --strict_checks and typescript eslint checks, I am trying to fix some new errors in my code. Code examples below for everything I explain. Say I have an Object a, and I want to directly specify it as a map to get around some errors. I can't use the keyword "any". This is what I am trying to do:

isEquivalent(a: Object, b: Object): boolean {
   const aObject: {[index: string]: Object} = a;
   const bObject: {[index: string]: Object} = b;
}

Link to the typescript playground with the actual code snippet: here But this throws the error:

error TS2322: Type 'Object' is not assignable to type '{ [index: string]: Object; }'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Index signature is missing in type 'Object'.

Can anyone point me to the solution for the type to specify object as, without using 'any'? Or if this isn't possible, please let me know.

1 Answers

const aObject: {[index: string]: Object} = a; assigns a (of type Object) to aObject (of type {[index: string]: Object}, an object with string property names and Object property values). But Object is not assignment-compatible with {[index: string]: Object}, so TypeScript gives you that error.

If you want to force it, you can do a type assertion:

const aObj = a as {[index: string]: Object};

Updated playground link

But beware that type assertions mostly disable TypeScript's type checking. The caller could pass in {a: 42}, which is not a {[index: string]: Object}, and TypeScript would allow it because you've said the parameter is just Object but then you're treating it as {[index: string]: Object}.

Sometimes that's appropriate, but you might consider giving the parameters the type {[index: string]: Object} instead of using a type assertion within the function. That way, TypeScript can ensure that only correctly-typed objects are passed in.

Related