如何键入枚举和对象具有相同的属性反应打字稿

发布于 2025-01-30 22:19:27 字数 377 浏览 1 评论 0原文

我有一个枚举:

enum INFO_CODES {
goToInit = 'goToInit',
lockIp = 'lockIp',

}

,我想创建一个具有相同属性(仅gotoinit和lockip)的对象(或枚举)

const SOME_OBJ = {
goToInit: function, //here i need function
lockIp: function,//here i need function
someProp:function //here i need mistake,can create only like in 
INFO_CODES props.

}

i have an enum:

enum INFO_CODES {
goToInit = 'goToInit',
lockIp = 'lockIp',

}

and i want to create an object(or enum also) with the same properties (only goToInit and lockIp)

const SOME_OBJ = {
goToInit: function, //here i need function
lockIp: function,//here i need function
someProp:function //here i need mistake,can create only like in 
INFO_CODES props.

}

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁与争疯 2025-02-06 22:19:28

您可以使用并只需使用enum作为密钥的第一个通用参数,然后将您要具有下一步的任何功能类型。

enum INFO_CODES {
  goToInit = 'goToInit',
  lockIp = 'lockIp',
}

type result = Record<INFO_CODES, () => void>;

const test: result = {
  goToInit: () => console.log("test"),
  lockIp: () => console.log("lockIp"),
}

You can use a Record and just use the enum as the first generic parameter for the key and then whatever function type you want to have next.

enum INFO_CODES {
  goToInit = 'goToInit',
  lockIp = 'lockIp',
}

type result = Record<INFO_CODES, () => void>;

const test: result = {
  goToInit: () => console.log("test"),
  lockIp: () => console.log("lockIp"),
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文