Here is a code snippet showcasing a sample function. The objective is to create a generic IncompleteVariant
that mirrors the properties of T
, but with all properties potentially unset.
The idea behind IncompleteVariant<T>
is that it should essentially be an empty object like {}
.
/**
* Modifies the passed `newState` to fallback on the `initialState` if any property is not set.
*/
export function orInitialState<T extends object> (newState: IncompleteVariant<T>, initialState: T): T {
type Key = keyof T;
if(!newState) return initialState;
const newerState: T = {...initialState}
for(const key of Object.keys(initialState)) {
if(newState.hasOwnProperty(key as Key)) newerState[key as Key] = newState[key as Key]
}
return newerState;
}
How can I define IncompleteVariant<T>
? My attempted solution so far has been:
/**
* Generic of object T but with all properties as optional.
*/
export type IncompleteVariant<T> = NonNullable<Partial<T>>
However, this results in the error message:
Type 'T[keyof T] | undefined' is not assignable to type 'T[keyof T]'. Type 'undefined' is not assignable to type 'T[keyof T]'.ts(2322)