Seeking a method to create a mapped type that excludes specific keys based on the value of the mapped key.
For instance:
Consider an option: Options
struct, where Options
is a union type defined as:
{ type: DataType } or { type: DataType, params: DataParam }
Within this union, some elements have a key named params
, while others do not. The goal is to construct such a union utilizing a mapped type. Here's a functioning solution (Playground Link):
type DataParams = {
trade: never;
trade_bar: {
interval: number;
intervalUnit: "ms" | "s" | "m" | "ticks" | "vol";
};
};
type DataTypes = keyof DataParams;
type OptionsForDataType<T extends DataTypes> = {
type: T;
} & (DataParams[T] extends never
? {}
: {
params: DataParams[T];
})
type Options = {
[DataType in DataTypes]: OptionsForDataType<DataType>;
}[DataTypes];
However, I find the approach using intersection + extends to be somewhat unsatisfactory. Is there a more elegant way to achieve the same outcome?
I had mistakenly assumed that when { key: never }
is used, the respective key is effectively excluded from the structure since nothing can be assigned to a key with the type never
. Surprisingly, this turned out not to be the case, which seems peculiar to me.