Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 484
Nahush Farkande Avatar asked Nov 16 '16 20:11

Nahush Farkande


People also ask

Is there an object type in TypeScript?

In TypeScript, object is the type of all non-primitive values (primitive values are undefined , null , booleans, numbers, bigints, strings). With this type, we can't access any properties of a value.

What is generic interface in TypeScript?

TypeScript - Generic Interface The above IProcessor is a generic interface because we used type variable <T> . The IProcessor interface includes the generic field result and the generic method process() that accepts two generic type parameters and returns a generic type. As you learned, you can use interface as type.

What is a generic type parameter?

Generic Methods A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

How can we create generic objects in JavaScript?

In JavaScript, there is the ability to create a generic anonymous object to serve this purpose. It can either be created using new Object() or the shorthand { ... } syntax, and can then be given any properties or methods that are needed.


2 Answers

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)

like image 96
Nitzan Tomer Avatar answered Oct 27 '22 01:10

Nitzan Tomer


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.

like image 42
JaredMcAteer Avatar answered Oct 27 '22 00:10

JaredMcAteer