I'm working with a type called ILoadedValue<TValue>
, which acts as a wrapper for types that can potentially be undefined
. However, I want to prevent situations where TValue
cannot be undefined
, as it's more efficient to use the actual value of undefined
to signify that the type is still loading.
Currently, my implementation involves using TValue extends undefined
.
/**
* {@link ILoadedValue} is necessary to provide atomic information
* about value and its loaded status for values that may be `undefined`,
* it should be used like `ILoadedValue<TValue> | undefined`
*
* Please note that we should steer clear of scenarios where `TValue` cannot be `undefined`
* (as in such cases, it's more efficient not to wrap the type,
* but rather to directly use `undefined` to indicate that the type is still being loaded)
*/
export interface ILoadedValue<TValue extends undefined> {
value: TValue;
}
However, when this type is utilized within another type, such as:
export class SomeClass<TValue> {
loadedValue: ILoadedValue<TValue | undefined> | undefined;
}
We encounter an error:
TS2344: Type
TValue | undefined
does not satisfy the constraintundefined
TypeTValue
is not assignable to typeundefined
SomeClass.ts(40, 3): This type parameter might need an extendsundefined
constraint.
Do you have any suggestions for an improved approach to address these conflicts?
export class SomeClass<TValue> {
// This should work
loadedValue: ILoadedValue<TValue | undefined> | undefined;
}
export class SomeClass2<TValue> {
// The compiler should raise an error here, as `TValue` is not guaranteed to include `undefined`
loadedValue: ILoadedValue<TValue> | undefined;
}