26 lines
798 B
TypeScript
26 lines
798 B
TypeScript
|
export function getComponentState<
|
||
|
State extends Object,
|
||
|
StateDefaultValueException extends keyof State | ""
|
||
|
>(
|
||
|
initialValues: Partial<Omit<State, StateDefaultValueException>> | undefined,
|
||
|
defaultValues: State
|
||
|
) {
|
||
|
type InitialValuesType = Omit<State, StateDefaultValueException>;
|
||
|
// const { initialValues } = props;
|
||
|
const getValue = (name: keyof InitialValuesType) => {
|
||
|
if (initialValues === undefined) return defaultValues[name];
|
||
|
return initialValues[name] !== undefined
|
||
|
? defaultValues[name]
|
||
|
: initialValues[name];
|
||
|
};
|
||
|
const state = {
|
||
|
...(Object.fromEntries(
|
||
|
Object.entries(defaultValues).map(([name]) => [
|
||
|
name,
|
||
|
getValue(name as keyof InitialValuesType) as any,
|
||
|
])
|
||
|
) as InitialValuesType),
|
||
|
} as State;
|
||
|
return state;
|
||
|
}
|