Generic Object type in typescript
In typescript is there any way to assign a variable a generic object type. Here's what I mean by 'generic Object type'
let myVariable: GenericObject = 1 // Should throw an error
= 'abc' // Should throw an error
= {} // OK
= {name: 'qwerty'} //OK
i.e. It should only allow javascript objects to be assigned to the variable and no other type of data(number, string, boolean)
Solution 1:
Sure thing:
type GenericObject = { [key: string]: any };
let myVariable1: GenericObject = 1; // Type 'number' is not assignable to type '{ [key: string]: any; }'
let myVariable2: GenericObject = 'abc'; // Type 'string' is not assignable to type '{ [key: string]: any; }'
let myVariable3: GenericObject = {} // OK
let myVariable4: GenericObject = {name: 'qwerty'} //OK
(code in playground)
Solution 2:
Typescript 2.1+ also has has a utility type, Record<K, T>
, you can use instead of making your own definition
const myObj: Record<string, any>;
I like to use the style described in top answer when I can give a meaningful name to key
but if it's not really as obvious or necessary Record
is a great option.