小编Har*_*ema的帖子

Typescript 根据先前参数的值推断可能的对象键?

我正在尝试建立翻译服务。用于翻译标签的函数应该提供对可能标签的类型检查,以及基于给定标签的替换对象的类型检查。

我有一个标签列表对象,它描述了可能的标签以及应出现在翻译后的字符串中的占位符列表。

export const TagList = {
    username_not_found: ['username']
};
Run Code Online (Sandbox Code Playgroud)

这种情况下的关键是字典应该实现的标签名称。该值是应出现在翻译字符串中的占位符列表。

字典看起来有点像这样:

// Note: The type declaration of keys don't work this way (key should be number or string). Not sure how I should implement this...
const en: {[name: keyof (typeof TagList)]: string} = {
    "username_not_found": "The user {username} does not exist"
}
Run Code Online (Sandbox Code Playgroud)

用于翻译标签的方法如下:

this.trans("username_not_found", {username: "someone@example.com"});
Run Code Online (Sandbox Code Playgroud)

我想要实现的是在 IDE 中对占位符对象进行类型检查(自动完成),以强制配置所有占位符。

例如:

// This is wrong: "username" placeholder is not specified.
this.trans("username_not_found", {});

// This is also wrong: "foobar" is a …
Run Code Online (Sandbox Code Playgroud)

typescript typescript-generics typescript-typings

2
推荐指数
1
解决办法
1845
查看次数