Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript, Type Object Is Not Generic

I am trying to create a type for an Object. But can't seem to get it right. This is what I have.

private test:Object<Test>;

this.test = {id : 'test'};

interface Test
{
   id : string;
}

This doesn't work. This gives me the following error:

Type Object Is Not Generic

What is the right way (syntax) to create types for Objects like this?

like image 629
Kris Hollenbeck Avatar asked Jun 22 '16 18:06

Kris Hollenbeck


People also ask

How do you define a generic object type in TypeScript?

To specify generic object type in TypeScript, we can use the Record type. const myObj: Record<string, any> = { //... }; to set myObj to the Record type with string keys and any type for the property values.

What is the type of an object 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.

Does TypeScript have generics?

TypeScript fully supports generics as a way to introduce type-safety into components that accept arguments and return values whose type will be indeterminate until they are consumed later in your code.

Does not exist on type object TypeScript?

The "Property does not exist on type Object" error occurs when we try to access a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.


1 Answers

Define a class Test:

export class Test {
  field1: number;
  field2: string;
  /// ...
}

then

private test:Test;

Update: Sorry, didn't notice you have Test as interface. It's fine too.

So same usage, you don't need Object<Test>, just Test

like image 91
Andrei Zhytkevich Avatar answered Sep 20 '22 04:09

Andrei Zhytkevich