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?
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.
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 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.
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.
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
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