SmxCde
SmxCde

Reputation: 5403

Is there a way to infer generic type from a generic type in TypeScript?

I have this function useFormState() that takes object initialValues of type FormType as an argument.

type FormType = {
    email: string;
    password: string;
    rememberMe: boolean;
}

...

const initialValues: FormType = {
    email: '',
    password: '',
    rememberMe: false,
}

const { values, touched, errors, updateField } = useFormState<FormType, keyof FormType>(initialValues);

Function useFormState() must return objects containing keys from FormType:

touched: {
    email: true,
    password: false,
    rememberMe: false
}

In order to be able to type the response like this I need to extract "keys" type, so I pass it as second generic type keyof FormType.

And this is what my question is about - Is there any way to pass just one type FormType and extract keys type internally?

My function is defined like this:

const useFormer = <T, K extends keyof T>(props) => {
  ...
}

I could completely omit passing types and let the TS to infer the types and it kinda works but

It feels like the second one can be completely inferred K extends keyof T but if I pass just one type argument - TS wants second one.

Is there any way to get away with just one?

Upvotes: 3

Views: 522

Answers (1)

Elias Schablowski
Elias Schablowski

Reputation: 2812

function fun<T>(a: T): {
  touched: {
    [key in keyof T]?: boolean;
  }
  values: T,
  errors: any[],
  updateField: () => void
} {
  ... // Do stuff with the inputs
}

TS Playground

This way you do not use a generic for the keyof, but rather have it computed in the function return type interface.

Upvotes: 1

Related Questions