When initializing my class, I often pass in either a value or an object containing information about the value. For instance:
new Field<string>('test')
new Field<string>({value: 'test', inactive: 'preview'})
However, I encounter an error with state.value
: "Property 'value' does not exist on type 'FieldState'. Property 'value' does not exist on type 'T'.ts(2339)"
interface BoxedValue<T> {
value: T
inactive: 'disabled'| 'preview'| 'hidden'
}
type FieldState<T> = BoxedValue<T> | T
class Field<T> {
value: T
_pendingValue: T
constructor(state: FieldState<T>) {
if(typeof state === 'object') {
this.value = this._pendingValue = state.value
} else {
this.value = this._pendingValue = state
}
}
}
I appreciate your solution in adjusting the code, but now I have encountered a new issue.
class Field<T> {
value: T
_pendingValue: T
constructor(state: FieldState<T>) {
if(this._isBoxedValue(state)) {
this.value = this._pendingValue = state.value // Property 'value' does not exist on type 'FieldState<T>'.Property 'value' does not exist on type 'T'.
} else {
this.value = this._pendingValue = state
}
}
_isBoxedValue(state: FieldState<T>): boolean{
return typeof state === 'object' && state !== null &&
Object.keys(state).length === 2 && 'value' in state && 'inactive' in state;
}
}
I wonder why putting the conditional check in the _isBoxedValue
function instead of the constructor led to errors. Can you help me understand?