Home > OS >  how to return a spread object in typescript
how to return a spread object in typescript

Time:08-29

I am making a custom hook in react with typescript, and I need to return a spread of the state, when I use the <T extends object> it works correctly, but I need to specify that this object has string values and this causes that when returning 2 or more objects, values, functions, etc. I get the following error

Error:

Property 'name' does not exist on type '{ reset: () => void; }

Interface:

interface IState {
    [key:string]: string;
};

Function:

const myFunction = (initialState:IState) => {
    const [state,setState] = useState(initialState)
    const reset = () => setFormState( initialState );
    return { reset, ...state }
}

File with the import:

const {
        name, ■ Property 'name' does not exist on type '{ reset: () => void; }'.
        reset,
    } = useForm({
        name: 'hello',
    });

when I only do return { ...state } this error does not appear, and if I add more, the interface of each one appears in the error

CodePudding user response:

Problem

You still have to specify that the name property exists:

Solution

Interface:

interface IState {
    [key:string]: string;
};

Function (actual change is here):

const useForm = <T extends IState>(initialState: T) => {
    const [state,setState] = useState(initialState)
    const reset = () => setFormState( initialState );
    return { reset, ...state }
}

Usage:

const {
    name,
    reset,
} = useForm({
     name: 'hello',
});
  • Related