Created
March 30, 2022 07:16
-
-
Save o-az/6d20a5a353027c9c6455fb5579f279ea to your computer and use it in GitHub Desktop.
Object.keys(obj) array to string literal types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// don't use this. I'm not sure if this is a good solution | |
// keeping it as notes till I find a better solution | |
// assume you got this from a JSON file: | |
const statesWeather = { | |
"wisconsin": "cloudy", | |
"california": "rainy", | |
"newyork": "sunny", | |
"florida": "cloudy", | |
"texas": "rainy", | |
} | |
const states = Object.keys(statesWeather) as Array<keyof typeof statesWeather> | |
type State = typeof states[number] | |
const test: State = 'wisconsin' | |
// ✅ 'const test: "wisconsin" | "california" | "newyork" | "florida" | "texas"' | |
// what if you want an object like this? | |
const attempt_one: Record<State, string> = { wisconsin: '' } | |
// ❌ Type '{ wisconsin: string; }' is missing the following properties from type 'Record<"wisconsin" | "california" | "newyork" | "florida" | "texas", string>': california, newyork, florida, texas ts(2739) | |
// possible solution: | |
type DeepPartial<T> = { [K in keyof T]?: DeepPartial<T[K]> } | |
const solution: DeepPartial<typeof statesWeather> = { | |
wisconsin: '', // ✅ | |
} | |
const solution_verify: DeepPartial<typeof statesWeather> = { | |
wisconsin: '', // ✅ | |
alaska: '', // ❌ | |
// Type '{ wisconsin: string; alaska: string; }' is not assignable to type | |
// 'DeepPartial<{ wisconsin: string; california: string; newyork: string; florida: string; texas: string; }>'. | |
// Object literal may only specify known properties, and 'alaska' does not exist in type | |
// 'DeepPartial<{ wisconsin: string; california: string; newyork: string; florida: string; texas: string; }>'.ts(2322) | |
} | |
const alternative_solution: DeepPartial<Record<State, string>> = { | |
wisconsin: '', // ✅ | |
} | |
const alternative_solution_verify: DeepPartial<Record<State, string>> = { | |
wisconsin: '', // ✅ | |
alaska: '', // ❌ | |
// Type '{ wisconsin: string; alaska: string; }' is not assignable to type | |
// 'DeepPartial<Record<"wisconsin" | "california" | "newyork" | "florida" | "texas", string>>'. | |
// Object literal may only specify known properties, and 'alaska' does not exist in type | |
// 'DeepPartial<Record<"wisconsin" | "california" | "newyork" | "florida" | "texas", string>>'.ts(2322) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment