Scenario: I am dealing with multiple select boxes filled with various select options.
Here are the different types that I am working with:
type Option<T = any> = {
value: T
// reserved for option
[prop: string]: any
}
export type OptionType<T = any> = Option<T>
interface SelectBox {
affiliate_id: number
campaign_id: string
username: number | string | undefined
}
interface SelectBoxOptions {
affiliate_id_options: OptionType<number>[]
campaign_id_options: OptionType<string>[]
username_options: OptionType<number | string | undefined>[]
}
Is there a way to automate the creation of the SelectBoxOptions
type, considering it follows a consistent pattern?
I attempted the following approach:
export type SelectBoxOptions<T> = {
[K in keyof T as `${K}_options`]: OptionType<T[K]>[]
}
An example use case is demonstrated below:
//
// interface NumberFilter {
// affiliate_id: number
// campaign_id: string
// }
//
// SelectBoxOptions<NumberFilter> == {
// affiliate_id_options: OptionType<number>[]
// campaign_id_options: OptionType<string>[]
// }
//
However, I encountered this error from tsc
:
https://i.sstatic.net/IrHRv.png
app/javascript/app/services/FilterService.ts:51:25 - error TS2322: Type 'K' is not assignable to type 'string | number | bigint | boolean'.
Type 'keyof T' is not assignable to type 'string | number | bigint | boolean'.
Type 'string | number | symbol' is not assignable to type 'string | number | bigint | boolean'.
Type 'symbol' is not assignable to type 'string | number | bigint | boolean'.
51 [K in keyof T as `${K}_options`]: OptionType<T[K]>[]
I am puzzled about why this generic type is causing an error. It appears correctly on hover in VSCode when I employ it...
If anyone knows how to prevent the error on "K" in ${K}_options
, please share!