Home > Software design >  Providing only some properties of a type instead of all properties during an onChange event
Providing only some properties of a type instead of all properties during an onChange event

Time:07-08

Suppose I have the following:

type TState = {
    open: boolean;
    text: string;
}

let state = {
    open: false,
    text: ''
}

type TSetState = {
    payload: TState;
}
const setState = ({ payload }: TSetState) => {
    state = {
        ...state,
        ...payload
    }
}

const handleChange = (text: string) => {
    setState({ payload: { text } })
//             ^^^^^^^
//             error here
}

This throws the error,

Property 'open' is missing in type '{ text: string; }' but required in type 'TState'

Obviously, if I do setState({ payload: { text, open: false } }), this fixes the issue, but how can I type this, so that I can only provide one property? I've tried doing keyOf TSetState, but that didn't work.

CodePudding user response:

By default all properties of a type are required. You need to mark it as optional which can be done by using the Partial<T> type.

type TSetState = {
    payload: Partial<TState>;
}

CodePudding user response:

You could also use Omit to achieve this:

const setState = ({ payload }: Omit<TSetState, 'open'>) => {
    state = {
        ...state,
        ...payload
    };
};
  • Related