Konrad Viltersten
Konrad Viltersten

Reputation: 39058

How to declare TS type that is an array of object that have properties with value of type number or string?

I have an input to my component that I declared like this.

@Input() rows: (string | number)[][];

I understand this is an array of strintegers (string or number), which I have an array of. So the data is a matrix, two dimensions, with strintegers (of floaties but in my case, it's not).

Realizing that not each row will have the same element count, I had to re-work the matrix into a dictionary, i.e. an array of objects (where the objects have properties we know nothing about, except that those are strintegers only). This is my best attempt.

@Input() rows: { [key: string]: (string | number) }[];

While the computer seems to accept it, I fear two things. First one being that it's plain wrong syntax and that I'm only ignorant of the issue due to poor testing. Second one being that regardless of correctness, I've created an atrocious enigma no eyes should ever behold (i.e. there's a perfectly neat way to express the same data structure).

How would one go about declaring a type as specified above in a better way than the one suggested?

Upvotes: 0

Views: 102

Answers (2)

wentjun
wentjun

Reputation: 42516

It seems like valid TypeScript to me. If I were you, I would clean up the typings such that I would declare an interface which could be reused in other components (perhaps the parent, which is the source of the input, or child, if you decide to further pass it on?).

export interface Row {
  [key: string]: string | number;
}

And then, within your component itself, you can import the interface and use it to declare the input typings.

@Input() rows: Row[];

Another approach, as suggested by @aleksayl., would be to apply a default GP type from TS like so.

Record<string, string | number>[]

Upvotes: 3

Ali Nasserzadeh
Ali Nasserzadeh

Reputation: 1449

Your code is perfectly fine, don't worry about it. However, it can be a good idea to move your model into an interface, like such:

interface Row {
  [key: string]: string | number;
}

As a side note: your syntax cannot be 'plain wrong' if your compiler/transpiler accepts it as valid Typescript - that doesn't always mean there isn't a better way however.

Upvotes: -1

Related Questions