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)
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.
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With