Home > other >  Is there a better way to write this Typescript type for storing api method calls?
Is there a better way to write this Typescript type for storing api method calls?

Time:08-01

I'm trying to find a way to improve either GenericActionables or Items so that the name of the api method doesn't need to be added as a GenericActionables<"nameOfNewMethod"> to the Actionables type every time so they are always in sync. Ideas appreciated thank you :)

interface API {
    playSound: (id: string, volume: number) => void,
    playPool: (id: string, randomize: boolean) => void
}

type GenericActionables<T extends keyof API> = {
    method: T,
    params: Parameters<API[T]>
}

// Is there a way to write this in a better way
// as not to have to update this type
// whenever the api gets added functionality so that they are always in sync?
type Actionables =
    GenericActionables<"playSound"> |
    GenericActionables<"playPool">

export const actionables: Actionables[] = [
    {method: "playSound", params: ["quack", 0.8]}, // this should work
    {method: "playSound", params: ["quack", true]}, // this should NOT work
    {method: "playPool", params: ["smack", true]}, // this should work
    {method: "playPool", params: ["smack", 0.8]}, // this should NOT work
]

CodePudding user response:

You can use mapped types:

Full code in TS Playground

type Values<T> = T[keyof T];
type Actionables = Values<{ [K in keyof API]: GenericActionables<K> }>;
  • Related