Typescript:如何从索引签名中删除密钥?

发布于 2025-01-13 05:04:11 字数 485 浏览 3 评论 0原文

在我基于 Angular 的 Web 应用程序中,我们有时需要一种类型来保存不同语言的各种字符串的翻译。然后,一位同事为此目的实现了这种类型:

export class TranslatedString {
  [language: string]: string;
}

显然,这称为索引签名,但我自己从未真正使用过它,所以我不太了解它是如何工作的。当我在运行时检查这个实例时,它看起来像这样:

{de: "TestDE", en: "TestEN", fr: "TestFR"}
de:"TestDE"
en:"TestEN"
fr:"TestFR"
__proto__:{}

我现在处于需要删除这种类型的翻译的情况,但我无法找到一种方法来做到这一点。似乎没有一个删除或删除函数,我可以调用它来通过其键删除元素。真的没有办法做到这一点吗?或者如何从 TranslatedString 实例中删除翻译?

In my Angular based web application, we at some point needed a type to hold translations of various strings in different languages. A colleague then implemented this type for that purpose:

export class TranslatedString {
  [language: string]: string;
}

Apparently, this is called an Index Signature, but I never really used it myself so I don't exactly understand how it works. When I inspect an instance of this at runtime, it looks like this:

{de: "TestDE", en: "TestEN", fr: "TestFR"}
de:"TestDE"
en:"TestEN"
fr:"TestFR"
__proto__:{}

I am now in a situation where I need to delete a translation from this type, but I cannot figure out a way to do it. There does not seem to be a remove or delete function which I can call to remove an element via its key. Is there really no way to do this, or how can I remove a translation from an instance of TranslatedString?

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

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

发布评论

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

评论(1

一念一轮回 2025-01-20 05:04:11

在运行时,您获得的对象是一个普通的 JavaScript 对象,

translations = {de: "TestDE", en: "TestEN", fr: "TestFR"}

因此 delete 应该可以做到这一点:

delete translations['de']

 // or 

delete translations.de

At runtime the object you are getting is a normal JavaScript object

translations = {de: "TestDE", en: "TestEN", fr: "TestFR"}

so a delete should do it:

delete translations['de']

 // or 

delete translations.de
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文