有没有更好的方法来编写用于存储api方法调用的Typescript类型



我正试图找到一种方法来改进GenericActionablesItems,这样api方法的名称就不需要每次都作为GenericActionables<"nameOfNewMethod">添加到Actionables类型中,这样它们就总是同步的。感谢您的想法:(

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
]

您可以使用映射类型:

TS游乐场中的完整代码

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

最新更新