1

Let's suppose I have the following object type:

type Test = {
  date: Date
  num: number
  str: string
}

As you can see there is a Date type that I want to convert to a string ("serialize"), so I created the following Generic Type:

type Serializer<T extends {[key: string]: unknown}> = {
  [key in keyof T]: T[key] extends Date ? string : T[key]
}

Which does the job very well, you can check this playground link.

playground result

But know, what if I have a Test[] type, what generic type could help me "serialize" this data type?

2
  • Wouldn't you just do type Result = Serializer<Test>[] to get it as array? Why would you want a serializer generic that takes in an array type? Commented Oct 2, 2022 at 21:46
  • 1
    Because that's what I have as result of a query, something like the Test[] type, but I also have a method that "serialize" that Test[] object and transforms the Date to a string, but unfortunately TS does not infer it, so I have to cast it manually. Commented Oct 2, 2022 at 21:56

1 Answer 1

1

To achieve a serializer generic that takes an array as input, you would require a custom ArrayElement type that would get the type of an element in your array.

Then your serializer has 2 generic types, the array (A) and the array element (T) which is equal to ArrayElement<A>

Here's an example:

type ArrayElement<A> = A extends readonly (infer T)[] ? T : never;

type Serializer<A extends Array<{ [key: string]: unknown }>, T = ArrayElement<A> > = {
  [key in keyof T]: T[key] extends Date ? string : T[key];
};

type Result = Serializer<Test>
//  type Result = {
//     date: string;
//     num: number;
//     str: string;
// }

Edit: You can one line the ArrayElement although I think this gets pretty messy and unreadable.

type Serializer<A extends Array<{ [key: string]: unknown }>, T = A extends readonly (infer T)[] ? T : never > = {
  [key in keyof T]: T[key] extends Date ? string : T[key];
};
Sign up to request clarification or add additional context in comments.

2 Comments

no need for infer, just use A[number]
Btw, at the end of the Serializer type you have to add [] to "cast" properly from an array to another array.

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.