å ¬éæ¥: 2021-08-10
æŽæ°æ¥: 2021-08-10
äŸãã°ä»¥äžã®ãããªObjectãæ±ããšããŸãã
const translations = {
ja: {
title: "ããã«ã¡ã¯",
body: "ã¯ãããŸããŠ"
},
en: {
title: "Hello"
body: "Nice to meet you"
}
}
ãŸããtranslations
ã®keyã¯ja, en, zhãªã©ã®èšèªã³ãŒãã®ã¿ã«ããããšããŸãã
ãã®å ŽåãTypeScriptã®key in
ã䜿ã£ãŠtranslations
ãåå®å
šã«ããããšãã§ããŸãã
type Language = "ja" | "en" | "zh"
type Translation = {
title: string;
body: string;
}
// { [key in TypeA]: TypeB }
const translations: { [key in Language]?: Translation } = {
ja: {
title: "ããã«ã¡ã¯",
body: "ã¯ãããŸããŠ"
},
en: {
title: "Hello",
body: "Nice to meet you"
}
}
translations.zh = { title: "äœ å¥œ", body: "å次è§é¢" } // OK
translations.ja = "ããã«ã¡ã¯" // Error!
translations.foo = "foo" // Error!
以äžã§ãã