teslamotors / informed

A lightweight framework and utility for building powerful forms in React applications
https://teslamotors.github.io/informed
MIT License
956 stars 173 forks source link

TypeScript - Examples of using unknown types? #425

Open ryanmunger opened 2 years ago

ryanmunger commented 2 years ago

Are there any examples of how to use types properly using the unknown type? Struggling with getting informed v4 set up in my project.

Specifically some advice on how to type useField/useState stuff so it's not unknown:

const { fieldState, fieldApi } = useField<string, string>(props);

is what i tried, it (the compiler) accepts that line, but using fieldState.value returns an unknown type which doesn't play well with other types.

Thank you in advance!

joepuzzo commented 2 years ago

I personally dont use typescript but what I do know is in trying to make the types NOT unknown from informed when you get nested forms it becomes hell on earth. If some Typescript GURU wanted to come in and help me figure out better way to do it im all ears but even within my company I had a few TS people go back and forth on different solutions and never came to consensus ( ONE OF THE REASONS I HATE TS SO F$%ing much... you ask 3 devs how to type something you get three answers ) ... Ryan do you miss my energy?? lmao

denno020 commented 7 months ago

@joepuzzo Is it possible to share a nested forms instance that we could use to hack types against?

In my projects, we're manually typing FormState to use a generic:

export type FormState<T> = {
  pristine: boolean;
  dirty: boolean;
  disabled: boolean;
  submitted: boolean;
  valid: boolean;
  invalid: boolean;
  submitting: boolean;
  validating: number;
  gathering: number;
  values: T;
  maskedValues: T;
  errors: Partial<T>;
  touched: Partial<T>;
  modified: Partial<T>;
  dirt: Partial<T>;
  focused: Partial<T>;
  initialValues: T;
  data: T;
  memory: T;
};

which works for my immediate issue, but I am by no means a TS guru. I too have been very resistant to TS, as it makes source code super ugly, but the code completion it offers is hard to ignore - and I guess the static type checking, but I find myself mostly fighting that, and only loving code completion.

joepuzzo commented 7 months ago

haha Its funny because Sooo many people I talk to share your exact same opinion on TS. Only really love it for the code completion. I share that sentiment. What do you mean exactly by "share a nested forms instance" ?

denno020 commented 7 months ago

From your comment above:

trying to make the types NOT unknown from informed when you get nested forms it becomes hell on earth

I assume you mean something like:

<Form>
  <Form></Form>
</Form>

But wanted to make sure?