[英]Typescript creating a type with keys based on union type
I have a translation object that can have keys corresponding to all of the languages a string might be translated in and the values being the translated strings, like so:我有一个翻译 object ,它可以有对应于所有语言的键,字符串可能被翻译,值是翻译的字符串,如下所示:
const trans = {
en: "Hello, how is it going?",
de: "Hallo, wie gehts?",
da: "Hej, hvordan går det?"
}
I am currently typing the object like so:我目前正在输入 object,如下所示:
type TransType = {
[key: string]: string;
}
But I also have a union type used in other places to control what languages can be implemented:但我也有其他地方使用的联合类型来控制可以实现哪些语言:
type Languages = "en" | "de" | "da";
How can I bring these two together and control what keys can be used in the trans object based on the Languages union type?如何将这两者结合在一起并根据语言联合类型控制在反 object 中可以使用哪些键?
You can use a mapped type for this ( docs ):您可以为此使用映射类型( 文档):
type Languages = "en" | "de" | "da"
type TransType = {
[key in Languages]: string
}
// infers TransType = { en: string, de: string, da: string }
const trans: TransType = {
en: "Hello, how is it going?",
de: "Hallo, wie gehts?",
da: "Hej, hvordan går det?",
nl: "Onbekende taal" // Error, as 'nl' is not in Languages
}
Or, as rshepp mentioned, you can use the Record
utility type ( docs , src ), which will define the same mapped type:或者,正如 rshepp 所提到的,您可以使用
Record
实用程序类型( docs 、 src ),它将定义相同的映射类型:
type TransType = Record<Languages, string>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.