首页 > 解决方案 > 是否可以在 Typescript 中提取这种类型?

问题描述

这段代码不起作用,但我想知道是否有办法以基于 svc 参数提供的值的方式键入方法参数?

interface Registry {
  "a": {
    get: () => {},
  },
  "b": {
    get: () => {},
    delete: () => {},
  }
}

function callService(svc: keyof Registry, method: keyof Registry[svc]) {} // method type here is wrong

// expected compile errors
callService("a", "get") // ok
callService("b", "get") // ok
callService("b", "delete") // ok
callService("a", "delete") // compile error

标签: typescript

解决方案


是的!可以使用泛型

function callService<T extends keyof Registry>( // Define a generic named T for this function.
   svc: T, // The generic will take this value.
   method: keyof Registry[T] // We can use the generic for other typings.
) {}

在此处输入图像描述 打字稿游乐场


推荐阅读