T
T
tron212022-02-02 17:27:00
typescript
tron21, 2022-02-02 17:27:00

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)
        ];
    };


An error occurs with the propertyName value.


TS2339: Property 'propertyName' does not exist on type '{ id: number; subtitle:string; important: boolean; done: boolean; }'.


I know for sure that propertyName will be either important or done from the type TodoListArrayType . But I can't find any information (or understand it correctly) in any way how to convey this information in the code. Please tell me how to correctly pass the type for propertyName.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2022-02-02
@timofeus91

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)
        ];
    };

Better yet, keep the TODO object by key (for mutations) and a separate list of IDs (for rendering the list) so that O(n) is not driven for each change.

R
Roman, 2022-02-02
@r_zaycev

Everything swears correctly, because the `propertyName` field is really not in TodoListArrayType and you have an error in your code
. You need to address it as `oldItem[proprtyName]`. But it is not a fact that the linter will not swear at this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question