Reputation: 21
I am confused about the correct way to fix an error in the block of code below.
public static getByProps = (values: object | object[]) => {
Array.isArray(values) ? (values = values) : (values = [values] as object[]);
let keys = Object.keys(values);
let dbArr = keys.map(key => `${Notes.tableName}.${key}`);
values = values.map(value => keys.map(key => value[key]));
return Notes.getQuery(builder => builder.whereIn(dbArr, values));
};
The input for this function should be either an object or an array of objects. If the function receives a single object, I convert that object to an array of objects with one element. I chose to do this because I don't have to worry about formatting when making calls from other parts of the code base.
Typescript throws error TS2339: Property 'map' does not exist on type 'object | object[]'
for the line of code below.
values = values.map(value => keys.map(key => value[key]))
I understand that Typescript thinks values can be an object which wouldn't have the property map, but I am not exactly sure how to cast it, or how to properly restructure my code. Can anyone explain this problem to me?
Upvotes: 1
Views: 3271
Reputation: 469
Typescript is giving you a valid linting error, because your union type of object | object[]
doesnt always have a method map
. because in the case that its an object, it would not exist. Since you are reassigning on the same variable, it is expecting that the value follows the same convention. Thus is gives you an error.
What you should probably do is create a new variable within the scope of your function which can only be an array of objects.
public static getByProps = (inputValues: object | object[]) => {
let values : object[] = Array.isArray(inputValues) ? inputValues : [inputValues];
let keys = Object.keys(values);
let dbArr = keys.map(key => `${Notes.tableName}.${key}`);
let valueKeyMap = values.map(value => keys.map(key => value[key]));
return Notes.getQuery(builder => builder.whereIn(dbArr, valueKeyMap));
};
Upvotes: 2