I have this type where my value property is "optional" (if T is not undefined)
type AsyncState<T = undefined> = {
value?: T;
loading: boolean;
error: { reason: string } | null;
}
Now I need to somehow create new object that depends on AsyncState parameter - add value property if T is not undefined and don't if T is undefined. (this is just dummy example of more complicated logic, but since types are problem, it should be enough)
function asyncGet<T>(initialState: AsyncState<T>) {
return typeof initialState.value !== 'undefined'
? (s: AsyncState<T>) => ({ ...initialState })
: (s: AsyncState) => ({ loading: initialState.loading, error: initialState.error });
}
const first: AsyncState<string> = {
loading: true,
error: null,
value: ""
}
const second: AsyncState<string> = {
loading: true,
error: null,
value: ""
}
const creator = asyncGet(first);
/*
Argument of type 'AsyncState<string>' is not assignable to parameter of type 'AsyncState<string> & AsyncState<undefined>'.
Type 'AsyncState<string>' is not assignable to type 'AsyncState<undefined>'.
Type 'string' is not assignable to type 'undefined'.
*/
creator(second);
Here is typescript playground.
type AsyncState<T> = {loading: boolean; error: {reason: string} | null; value?: T | null}? The difference seems small enough and it would have to be easier to deal with...valueis optional as in{value?: T | null}then you don't needvalue: null, right? It would just be left out. I could possibly take as given that you need to use the relatively clunky conditional type, but I'd like to see a minimal reproducible example here with actual use cases. As it stands I don't how to proceed (what'scombineReducers()? This question is not taggedreduxand if you need redux expertise then it probably should be... if it's not about redux then make some example use cases without being dependent on it). Good luck!