Given the types defined as:
type A = { commonKey: { a: string }[] };
type B = { commonKey: { b: number }[] };
Is it possible to create the type below without explicitly specifying commonKey
?
type C = { commonKey: { a: string, b: number }[] }
My initial attempt with type C = A & B
did not give the desired result:
const c: C = // ...
c.commonKey.map(x => x.a) // This works for `a` but not for `b`
I am looking for a generic solution that can combine the types regardless of the key name:
type ArrayContent = A['commonKey'][number] & B['commonKey'][number]
type C = { commonKey: ArrayContent[] };
Background
Using TypeScript 4.1 template literal types and recursive conditional types, I am enhancing the types for Elasticsearch queries in our project. We have a predefined type for the documents in our Elasticsearch cluster:
interface Post {
id: string;
title: string | null;
author: {
name: string;
};
comments: {
id: string;
message: string;
}[];
}
At runtime, Elasticsearch allows limiting the fields to retrieve using paths, without distinguishing between keys within an array or a regular object.
const sourceFields = ['id', 'author.name', 'comments.message'];
I am developing a new type that, based on the document type and source fields, will determine the retrieved fields. Here is the current progress:
// TypeScript code snippet provided
// Usage example showing the type inference
It works well for handling undefined
or null
values and nested objects. However, when attempting to retrieve multiple fields within an array (
['comments.id', 'comments.message']
), the mentioned issue arises. Any suggestions for a solution?