0

Please, tell me, can I do this with ts? I have next source code:

interface FormStore<T> {
  type: T;
}

interface Form<T> extends FormStore<T> {
  email: T;
  phone: T;
  password: T;
}

interface FormState<R> {
  form: Form<string>;
  validate: Form<boolean>;
}

I want to reuse type FormState<R> and create new with argument. It something looks like replace Form on R:

// This example doesn't work, just only for example
interface FormState<R> {
  form: R<string>;
  validate: R<boolean>;
}

// another file
FormState<CustomForm>
5
  • R<string> it will not work. TS does not support higher kinded types Commented Oct 2, 2021 at 19:50
  • @captain-yossarian yes, and because I ask: how do it? I showed plan, implementation can be any Commented Oct 2, 2021 at 19:53
  • Does this approach work for you? Without true higher-kinded types in TypeScript, you can only simulate them via something like a registry. Anytime you create a new type you want to use like this, you need to add it to the registry. If that approach works for you I can write up an answer; if not, please edit the code to show failed use cases. Commented Oct 2, 2021 at 20:39
  • @jcalz it is the best way for me for now. Commented Oct 2, 2021 at 21:18
  • @reznikovkg When you say "for now" does that mean you're waiting for other suggestions? I'm trying to decide whether to write up an answer for you. Commented Oct 2, 2021 at 21:22

1 Answer 1

1

From your original declaration, this is the best I can do for now. If you don't make set a default type parameter for FormStore & Form, you will have to explicitly use type FormStateF = FormState<Form<unknown>>;, which is awkward.

interface FormStore<T = unknown> {
  type: T;
}

interface Form<T = unknown> extends FormStore<T> {
  email: T;
  phone: T;
  password: T;
}

interface FormState<R> {
  form: { [x in keyof R]: string };
  validate: { [x in keyof R]: boolean };
}

type FormStateF = FormState<Form>;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.