qiniu / formstate-x

Manage state of form with ease.
https://qiniu.github.io/formstate-x
MIT License
34 stars 10 forks source link

Type-safe `safeValue` #58

Open nighca opened 3 years ago

nighca commented 3 years ago

safeValue is like $ of FieldState in formstate-x v2, while with some differences:

  1. Naming as safeValue (or something else) instead of $
  2. All states (including FormState, ArrayFormState, etc.) will provide safeValue
  3. It should be type-safe (deciding by validators - they may narrow type of value)
nighca commented 3 years ago

Related discussion: https://github.com/qbox/horn/pull/340#discussion_r699824181

nighca commented 3 years ago

Some ideas:

1. Auto type inference by validators

const state = new FieldState<string | null>('').validators(notNull) // safeValue: string

It's hard, maybe impossible

2. Generic type passing with validator

const state = new FieldState<string | null>('').validators<string>(notNull) // safeValue: string

3. Generic type passing with constructor

const state = new FieldState<string | null, string>('').validators(notNull) // safeValue: string

4. Type assertion while read safeValue

const state = new FieldState<string | null>('').validators(notNull)
const safeValue = state.safeValue! // string

This is not real "type-safe"..

mattleonowicz commented 2 years ago

One thing to consider: should this value be defined and available even when validators return errors? If not, then 2. makes sense.

But if this value is always defined, regardless of latest validation result, then I would suggest not linking the safeType with validators as in 2.

nighca commented 2 years ago

One thing to consider: should this value be defined and available even when validators return errors?

Accessing safe-value will throw if currently validation not passed.

@computed get safeValue() {
  if (!this.validated || this.hasError) throw new Error('TODO')
  return this.value
}