I am attempting to create a type for an object, that I logged using console.log in javascript. I accessed my console to view the contents of this object, this is what I got
{
SomeAssets: [{id:"SomeArbitaryIdHere"}]
description: "SomeDescription here"
id: "SomeID"
SomeRef: "SomeProdRef"
}
How would I create a type of this, this is what I attempted but am unsure
export type = myObjectType
{
someAssets: Asset;
description: string;
id: string;
someRef: string;
}
export type = Asset
{
someArray: string[];
}
Is this correct?
I think you are looking for something like below. someAssets is an array of asset objects that have an id property
export type myObjectType =
{
someAssets: Asset[];
description: string;
id: string;
someRef: string;
}
export type Asset =
{
id: string;
}
The code in your question has several syntax errors and is not valid TypeScript. If you haven't already, you should consider going through some TypeScript documentation in the TypeScript Handbook; here is a place to get started.
Here's one possible way of defining some interfaces to represent your object:
interface MyObjectType {
someAssets: Asset[];
description: string;
id: string;
someRef: string;
}
interface Asset {
id: string;
}
And you can verify that your object is assignable to the MyObjectType interface:
const myObject: MyObjectType = {
someAssets: [{ id: "SomeArbitaryIdHere" }],
description: "SomeDescription here",
id: "SomeID",
someRef: "SomeProdRef"
}; // okay, no compiler error.
Do note that I had to change your object to be properly formatted; property key-value pairs in JavaScript object literals must be comma-delimited; you can't separate them with just a newline.
Also, since JavaScript is case sensitive, it's important that your object keys and the corresponding interface key names are exactly the same; I changed SomeAssets and SomeRef to someAssets and someRef, respectively, opting for lower- instead of upper- camel case. Key names conventionally begin with a lowercase character, but if your use case requires that the keys be SomeAssets and SomeRef instead, then you should change the keys in the interface to match it.
You may or may want to export your interfaces from a module, or use a type alias to an object type instead of an interface, as it looks like you might have been attempting to do; but whether or not you need to do those depends on your use cases. My advice to you is to get more familiar with TypeScript from the handbook and existing code written in TypeScript so you can understand both what your use cases are and how they can be supported by the language.