如何声明一种类型的对象的键和价值与TS中的枚举相关联?

发布于 2025-01-29 03:07:33 字数 2265 浏览 1 评论 0原文

如何在打字稿中声明对象的类型,其密钥是枚举的枚举成员,其值是一个函数,并且此函数的参数与密钥有关?

Details are as follows:

enum Type {
  'select'='select',
  'upload'='upload'
}

type selectProps = {
    options: any[],
    defaultCheckedValue: string
}
type uploadProps = {
  url:string[],
  request:()=>Promise<any>
}
// The otherConfig parameters of the select and upload functions are extended keys based on otherConfig
interface otherComonConfig{
  displayDependOnKeys:Record<string,any>
}
// How to define the correspondence between key and value
type RenderFunc = {
  [key in Type]:<T,U extends otherComonConfig,R>(prop:string,label?:string,options?:T,otherConfig?:U) => R
}

let map:RenderFunc = {
  [Type.select]:(prop,label,options,otherConfig) =>{
    return {
      prop,
      label,
      key:"select",
      options,
      otherConfig
    }
  },
  [Type.upload](prop,label){
    return {
      prop:"handleContent",
      key:'upload'
    };
  }
}
// I hope when i call this methods the options auto map selectOptions,
// At the same time I can also customize the otherConfig type 
// How can i achieve?
map.select('32','dwdw',);

I've tried many ways, but it always prompts the wrong type,Can anyone help me?

See the complete code here -- TS Playground

How to declare the type of an object in typescript, its key is an enumeration member of enum, its value is a function, and the parameters of this function are related to the key?

Details are as follows:

enum Type {
  'select'='select',
  'upload'='upload'
}

type selectProps = {
    options: any[],
    defaultCheckedValue: string
}
type uploadProps = {
  url:string[],
  request:()=>Promise<any>
}
// The otherConfig parameters of the select and upload functions are extended keys based on otherConfig
interface otherComonConfig{
  displayDependOnKeys:Record<string,any>
}
// How to define the correspondence between key and value
type RenderFunc = {
  [key in Type]:<T,U extends otherComonConfig,R>(prop:string,label?:string,options?:T,otherConfig?:U) => R
}

let map:RenderFunc = {
  [Type.select]:(prop,label,options,otherConfig) =>{
    return {
      prop,
      label,
      key:"select",
      options,
      otherConfig
    }
  },
  [Type.upload](prop,label){
    return {
      prop:"handleContent",
      key:'upload'
    };
  }
}
// I hope when i call this methods the options auto map selectOptions,
// At the same time I can also customize the otherConfig type 
// How can i achieve?
map.select('32','dwdw',);

I've tried many ways, but it always prompts the wrong type,Can anyone help me?

See the complete code here -- TS Playground

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文