Using TypeScript 4.6.4, I have a list of keywords and a Paragraph interface where these keywords are referenced:
const keyswordsAndSynonyms = {
keyword1: ["synonym1", "synonym2"],
keyword2: ["synonym3", "synonym4"],
} as const
interface Paragraph {
content: string
keywords: Array<keyof typeof keyswordsAndSynonyms>
}
const myParagraph: Paragraph = {
content: "bla bla",
keywords: ["keyword1", "foo dahoo"]
}
So far, so good. TypeScript complains that "foo dahoo" is wrong - as it should.
Now I want to type keyswordsAndSynonyms itself. (Just to be save so that no one can accidentally use a flat string as synonym or a number as keyword or whatnot.)
However, when typing keyswordsAndSynonyms as Record<string, readonly string[]>, the type restrictions for keywords stop working. I can now use "foo dahoo" without TypeScript complaining about it.
How come and how can I solve that?