I have a static dictionary:
const myDict = {
1: "one",
2: "two"
}
The default inferred type for this is Record<1 | 2, string>
.
I would like to derive a type that only accepts the exact string literals assigned to myDict
properties:
type T = {
1: typeof "one",
2: typeof "two"
}
How can I derive such type? Typing the original dictionary (so typeof myDict
would equal to my desired type) would work the best for me.
I know I can assert the type via as
keyword:
const myDict = {
1: "one" as typeof "one",
2: "two" as typeof "two"
}
but this workaround is very impractical and prone to error with large dictionaries. What would be a better approach?
You can accomplish this using a const assertion.
const myDict = {
1: "one",
2: "two",
} as const