I am trying to get to the WANTED
type from the definition of columns
.
declare class ColumnDefinition<T, R extends boolean = false, N extends string = string> {
typeValidator: (v: unknown) => v is T;
required: R;
name: N;
};
type columns = [
ColumnDefinition<number, true, 'ID'>,
ColumnDefinition<string, true, 'text'>,
ColumnDefinition<boolean, false, 'bool'>,
ColumnDefinition<bigint, false, 'bigint'>,
];
type WANTED = {
ID: number;
text: string;
bool?: boolean | undefined;
biging?: bigint | undefined;
};
I tried to look for ToupleFilter
methods, but they all seem to break when defining the recursive part.
type FilterColumns<
Required extends boolean,
COLUMNS extends readonly ColumnDefinition<any, boolean, any>[],
> = COLUMNS extends readonly [infer L, ...infer Rest]
? L extends ColumnDefinition<any, Required>
? [L, ...FilterColumns<Required, Rest>]
: FilterColumns<Required, Rest>
: [];
playground
In the code above specifically FilterColumns<Required, Rest>
the Rest
is highlighted and tells that unknown[]
is not assignable to readonly ColumnDefinition<any, boolean, any>[]
.
- Why is
Rest
defined asunknown[]
instead ofColumnDefinition<number, boolean, any>[]
? - How to fix this?
- (Bonus) If any bright mind has a solution to get the resulting object, it would be perfect!
PS: The FilterColumns
type does work, but the compiler is not happy about it…
Bonus part:
Given the above definition for columns
, I wanted to create this object. I
// My closest attempt so far
type Result<Cols extends readonly ColumnDefinition<any, any>[]> = {
[I in keyof FilterColumns<true, Cols>]: {
[N in ColumnName<FilterColumns<true, Cols>[I]>]: ColumnType<FilterColumns<true, Cols>[I]>;
};
}[number] & {
[I in keyof FilterColumns<true, Cols>]: {
[N in ColumnName<FilterColumns<false, Cols>[I]>]?: ColumnType<FilterColumns<false, Cols>[I]>;
};
}[number];
type RES = {
ID: number | string;
text: number | string;
} & {
bool?: boolean| bigint | undefined;
biting?: boolean| bigint | undefined;
}
My attempt seems like a lot of work for the compiler… hopefully, some bright mind might be able to provide a better idea of how to tackle the task at hand…