Reputation: 463
I am struggling to define a type for the array with named objects
below is the sample code.
now i have to define the type for the s
in typescript
let s =[12,3,4]
s['data']={'x':0}
console.log(s) // [12,3,4,data:{'x':0}]
now how to define the type
for the s
can anyone please guide
Upvotes: 0
Views: 897
Reputation: 1075239
It's probably best not to do this. But you can do it, by using an intersection type, in this case:
type AugmentedNumberArray = number[] & {
data?: {x: number};
};
That's a type that's both a number array and an object with an optional data
property that can be an object with an x
property with a number value.
But as soon as you do something like s2 = s.map(v => v * 2)
, you'll lose the data
property, because map
(like all array methods) only deals with the array-like part of the object, not any other properties it may have.
Instead, though, I'd recommend defining an object that has both the named properties (data
or whatever) and an array of numbers:
interface MyType {
data?: {x: number};
values: number[];
}
Then using it like this:
let s: MyType = {values: [12,3,4]};
s['data'] = {'x':0}; // Or idiomatically: s.data = ...
console.log(s);
Upvotes: 2