I would love to know if there is any way to avoid defining generics down a “long” chain of types. I am trying to use the type of parameter schema
to type the parameter values
.
Minimal example:
const IntegrationSchemas = {
URI: ['uri'],
URI_STORE: ['uri', 'storeId'],
} as const;
type IntegrationSchemaKeys = keyof typeof IntegrationSchemas;
type TranslationConfig<IntegrationSchemaKey extends IntegrationSchemaKeys> = {
schema: IntegrationSchemaKey;
values?: Record<(typeof IntegrationSchemas)[IntegrationSchemaKey][number], string | number | boolean>;
};
type TranslationConfigs = {
points?: TranslationConfig; // Generic type 'TranslationConfig' requires 1 type argument(s).
controls?: TranslationConfig; // Generic type 'TranslationConfig' requires 1 type argument(s).
};
const getTranslation = (configs?: TranslationConfigs) => {
...
};
getTranslation({
points: {
schema: 'URI', // Should give auto-completion
values: {
uri: 'some_uri', // Should give auto-completion
},
},
controls: {
schema: 'URI_STORE', // Should give auto-completion
values: {
uri: 'some_uri', // Should give auto-completion
storeId: 'some_store_id', // Should give auto-completion
},
},
});
I am trying to avoid having to define a generic type for each key-value pair in the TranslationConfigs
type and the getTranslation
function for that matter… AKA this is what I would rather not do:
type TranslationConfigs<PointsKey extends IntegrationSchemaKeys, ControlsKey extends IntegrationSchemaKeys> = {
points?: TranslationConfig<PointsKey>;
controls?: TranslationConfig<ControlsKey>;
};
const getTranslation = <PointsKey extends IntegrationSchemaKeys, ControlsKey extends IntegrationSchemaKeys>(configs: TranslationConfigs<PointsKey, ControlsKey>) => {
...
}
getTranslation<"URI", "URI_STORE">({
points: {
schema: 'URI',
values: {
uri: "some_uri",
},
},
controls: {
schema: 'URI_STORE',
values: {
uri: 'some_uri',
storeId: 'some_store_id',
},
},
});
In the not so nice example if the generics are not explicitly given, then the values
will always give auto-completion of a union of all possible values, fx, ["uri", "storeId"]
.
Any help is much appreciated!