I would like to create a type for the following:
categories.categories[0].category.map((c: CategoryObject) => ({
category: c.name[0]._text[0],
Is it possible to declare the index 0? like:
type CategoryObject = { name[0]: { _text: [0] } };
I would like to create a type for the following:
categories.categories[0].category.map((c: CategoryObject) => ({
category: c.name[0]._text[0],
Is it possible to declare the index 0? like:
type CategoryObject = { name[0]: { _text: [0] } };
There should be no reason to define the type of 0
if the array is homogeneous (i.e. all of its elements have the same type). Instead, you need to define CategoryObject as an object that has an array element called name
, and the elements of that array have a _text
element that itself is an array (probably of strings).
Furthermore, since you're not defining an alias for a primitive, union, or intersection, it is probably better to use an interface definition.
// Using arrays
interface TextContainer { _text: string[] }
interface CategoryObject { name: TextContainer[] }
Or, inline:
// Using arrays
interface CategoryObject = { name: { _text: string[] }[] }
The above is probably what you want, since it is likely that your data source will contain variable-length homogeneous arrays; however, if you instead want to insist that your arrays are fixed-length and may contain multiple types of data, you can change this to a tuple definition. (Internally a tuple is represented as an array, but TypeScript keeps track of each element's type separately.)
You can do this by listing the types as if they were an array literal, which in your case has one element. Note the difference between string[]
and [string]
, which would matter more if you had elements like [string, number, Foo]
:
// Using tuples
interface TextContainer { _text: [string] }
interface CategoryObject { name: [TextContainer] }
Or, inline:
// Using tuples
interface CategoryObject = { name: [{ _text: [string] }] }