#Typesafety for arrays with dynamic options model

6 messages · Page 1 of 1 (latest)

tiny gazelle
#

I have this function called toComboboxModel that accepts PropertyType | PropertyType[] as parameter.
I want to add typesafety based on what model the options are.

This is how I want to use the function:

    {
      options: stores,
      valueKey: 'storeId',
      labelKey: 'name',
    },
    {
      options: customers,
      valueKey: 'customerId',
      labelKey: 'name',
    },
  ]);```

in this case typescript doesn't suggest me the model for customers, only if there is only one object inside array it will. I guess typescript doesn't know when there are mixed generic models.

Here's the playground https://www.typescriptlang.org/play/?#code/C4TwDgpgBA8mwEsD2A7KBeKBvAUFKAbgIYA2ArhAFxQDOwATgigOZ5QlEBGEJ1djLHAF8cOJsAj0AZkQDG0AAr0kkeqAAq4CAB51APmxsViVDWrqA2gF02NHhFkSAJnBMoA-ObbFyEANIQINQA1oFIUlDqbBzcJAFBUKEg4ZHColJkKI7IaMBIAMJIALacSKUAHgCySE48unoAFGDKqogQZlBKKpIaWvUAlNSuOdbpmdmoUHmFJWVIVTV1+k0tPQjt1F2tIJqQ9daDsPAjVqM4GVluUwXFpRXVtST1DWzN3WrrHVs9O336UAAfTqrNS-Pb6UaHYaoayAo5uayw3D4AD0KKgCCKYBIECKEBQwCIbjSohwaKgRDAYBwslMwFoeXo7QwUAsyPwDKQTIAkk5qAAiACM-IANGx8CgiHiBQBlRnQGAoCCi8VQDIkEgAQScTiZNA6-PVJApOr1NBVQhsNLpUFkZDoxUkNBZbNVdodePovIFACYVRyoJLpVB+fl7XlPbAlf6OUbtbr2gajSaE-qLVbrSg6FBjDlnZhprc5gtHi8A+yA-hc6Y+PKaGLKxyfBR4tQAOQOnlONsiqDk3YQGWyRjwKAAdwQGtoZGYzHa9M7EF5vaDEF7RFNidVAZiPFbUDbq57ffRA6HI-pE6nNBnc+zi+Xgala5TZtVQgbHIrlerWeo7ojJ1P0bZt-ECdsAMdL1u17fstHPBBRxoAALJAyBIJxp1nedbXDKDH1XXs403fVtw5Xc4nAg8j1g094OHRCF1Q9DMJvbDs0gz0COfIj0K1EiaHfMV+iAA
misty larkBOT
#

@tiny gazelle Here's a shortened URL of your playground link! You can remove the full link from your message.

fitimbytyqi#0

Preview:```ts
type Option = {
value: string
label: string
}

interface PropertyType<T> {
options: T[]
selectedOption?: T
valueKey: keyof T
labelKey: keyof T
}

function toComboboxModel<T>(
properties: PropertyType<T>
): Option[]

function toComboboxModel<T>(
properties: PropertyType<T>[]
): Option[][]
...```

stone galleon
#

there's a trick you can do to get typescript to run its inference logic separately for each argument passed to a variadic function:

misty larkBOT
#
mkantor#0

Preview:ts ... type Properties<T extends readonly unknown[]> = { [K in keyof T]: PropertyType<T[K]> } function toComboboxModel<T extends readonly unknown[]>( ...properties: Properties<T> ) { // implementation throw "not implemented" } ...

tiny gazelle
#

@stone galleon Okay this implementation is what I was looking for, im assuming the spread operator is what turns the arguments into an array ?