Answer the question
In order to leave comments, you need to log in
How to correctly type the parameter?
Good day to all! I am making a universal function to change a boolean value in an object that is part of an array.
export type TodoListArrayType = Array<{
id: number,
subtitle: string,
important: boolean,
done: boolean,
}>
const generalToggle = (arr: TodoListArrayType, id: number, propertyName: any) => {
const idx = arr.findIndex((item) => item.id === id);
const oldItem = arr[idx];
const value = !oldItem.propertyName;
const item = {...arr[idx], [propertyName]: value};
return [
...arr.slice(0, idx),
item,
...arr.slice(idx + 1)
];
};
TS2339: Property 'propertyName' does not exist on type '{ id: number; subtitle:string; important: boolean; done: boolean; }'.
Answer the question
In order to leave comments, you need to log in
interface TodoItem {
id: number
subtitle: string
important: boolean
done: boolean
}
const generalToggle = (arr: TodoItem[], id: number, propertyName: keyof TodoItem) => {
const idx = arr.findIndex((item) => item.id === id);
const oldItem = arr[idx];
const value = !oldItem[propertyName];
const item = {...arr[idx], [propertyName]: value};
return [
...arr.slice(0, idx),
item,
...arr.slice(idx + 1)
];
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question