I am working on an Angular application. In that I have an interface IAbc
:
interface IAbc {
id: number,
name: string
}
And another interface IXyz
which uses the above interface like below:
interface IXyz {
id: number,
value: string | number | Date | IAbc[];
}
Here, the value can be of any type of data, so I have narrowed down on the types.
I have created a new variable:
let someVar: IXyz;
someVar = {
id: 100,
value: [
{
id: 1,
name: 'abc'
},
{
id: 2,
name: 'xyz'
}
]
};
Since the value can be a list also, I have to use forEach
on it to do some operation:
someVar.value.forEach((x: IAbc) => console.log('some operation on value, ', x))
But, I get this error on forEach
:
Property 'forEach' does not exist on type 'string | number | Date | IAbc[]'.
Property 'forEach' does not exist on type 'string'.(2339)
I think logically this should work. Is there something wrong with the typescript?
I have created a playground link, where I have reproduced this.
Let me know your thoughts. Thanks!
P.S.: I know I can use any
over there and it will work smoothly, but the usage of any
has been disabled by the linting of the application.
CodePudding user response:
To get rid of the error you can use a typeguard.
function isArray(value: string | number | Date | IAbc[]): value is IAbc[] {
return (value as IAbc[]).forEach !== undefined;
}
if( isArray(someVar.value) ) {
someVar.value.forEach((x: IAbc) => console.log('some operation on value, ', x))
}
You can see it working in an updated version of your playground here
CodePudding user response:
You need a typecast to tell the compiler this is indeed an array
(someVar.value as IAbc[]).forEach((x: IAbc) => console.log('some operation on value, ', x))