I have the following type:
type FormData = {
field1: string;
field2: string;
fieldₙ: string;
}
I want to create a function for React that receives just one key, and one value, being the key one of those in the previous type (FormData
).
So, in this case, I want to create a type that could encase the following:
{field1: string}
or {field2: string}
and all other potential fields.
Basically the idea is to being able to type a function like this:
(data: {field from FormData: string}): void
Is there any way to create a type like this?
I tried using [key in FormData]:string
, but that forces me to have all fields, and not just one.
I don’t want to make them all ignorable with ?
.
3
Answers
You can use Typescript Mapped Types and declare a type like this
You can also use this implementation with generics and template literal types
Edit
Since you want at least one key, you can use this implementation:
Something like this? Notice it supports different value-types for the fields, and the resulted-object is also typed.
Edit 1: Thinking about it, this problem could be abstracted to a generic type, and not be limited to FormData or a specified type:
Edit 2: The logic can be further extended to any number of keys from any object type:
You can use a self-indexing mapped type as follows:
Which gives you the following result type: