打字稿中的复杂类型

发布于 2025-01-19 11:41:01 字数 217 浏览 2 评论 0原文

我需要在我的接口中描述一个带有索引的字符串,在字符串的末尾也可以是工作或崩溃:

export interface Test {
    date: string,
   'stat.conv[index: number].key[index: number].(work || crash)': Test2[]
}

在Typescript中,这是否可以吗?

I need to describe in my interface a string with indexes also in the end of string can be work or crash:

export interface Test {
    date: string,
   'stat.conv[index: number].key[index: number].(work || crash)': Test2[]
}

Is this possible in typescript?

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

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

发布评论

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

评论(1

乖乖 2025-01-26 11:41:01

您可以使用 模板文字类型 来定义键:

export interface Test {
    date: string;
   [key: `stat.conv[${number}].key[${number}].${'work'| 'crash'}`]: any;
}

const t: Test = {
  date: '',
  'stat.conv[0].key[0].work': '', // OK
  'stat.conv[1].key[1].crash': '', // OK
  'stat.conv[x].key[y].work': '', // Error
  'stat.conv[0].key[0].nothing': '' // Error
}

You can use a template literal type to define the keys:

export interface Test {
    date: string;
   [key: `stat.conv[${number}].key[${number}].${'work'| 'crash'}`]: any;
}

const t: Test = {
  date: '',
  'stat.conv[0].key[0].work': '', // OK
  'stat.conv[1].key[1].crash': '', // OK
  'stat.conv[x].key[y].work': '', // Error
  'stat.conv[0].key[0].nothing': '' // Error
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文