After referring to my recent inquiry...
Can a default value be specified for valueProp
in this scenario?
type ValueType = 'value' | 'defaultValue'
type Props<T extends ValueType> =
Record<T, string>
function props<T extends ValueType>(valueProp: T): Props<T> {
return {
[valueProp]: 'value',
other: 'other'
} as Props<T>;
}
let { defaultValue, other } = props('defaultValue'); // valid
let { value } = props('value'); // acceptable
Attempting the following results in an error:
function props<T extends ValueType>(valueProp: T = 'value'): Props<T> {
return {
[valueProp]: 'value',
other: 'other'
} as Props<T>;
}
, which throws:
Type '"value"' is not assignable to type 'T'.
'"value"' is assignable to 'T', but could differ from 'ValueType'.
I comprehend this issue, yet I struggle with finding a suitable resolution.
Is there a straightforward approach to address my objective?
Default Type for Generic Type?
Considered the following:
function props<T extends ValueType = 'value'>(valueProp: T = 'value'): Props<T> {
return {
[valueProp]: 'value',
other: 'other'
} as Props<T>;
}
Still faced the same dilemma due to the possibility of selecting a different specific T
:
props<'defaultValue'>()
Type Assertions?
Utilized type casting, although it compiles, it fails to prevent discrepancies between valueProp
and T
:
function props<T extends ValueType>(valueProp: T = 'value' as T): Props<T> {
return {
[valueProp]: 'value',
other: 'other'
} as Props<T>;
}
console.log(props<'defaultValue'>());
// => {value: "value", other: "other"}
A More Elaborate Solution?
An uncomplicated remedy is desired, but if unavailable, perhaps a more intricate solution could suffice.
Could introducing a mapping table linking a type to its default value serve as inspiration?
For instance, consider:
Reference: 'CustomEnum.Case' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'CustomEnum'
Resource: https://github.com/microsoft/TypeScript/issues/29528#issuecomment-456804257