Created
February 13, 2020 00:34
-
-
Save pnappa/ac125c983be61524503529aef401bafc to your computer and use it in GitHub Desktop.
Failing at getting parametised runtime picking in typescript
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
// this doesn't work... I want to extract types from the process.env, and ensure they're required...! | |
// not an easy task it seems | |
function safeLoadEnv<T, K extends keyof T>(env: T, ...keys: Array<K>): Required<Pick<T, K>> { | |
// extension of https://stackoverflow.com/a/47232883 | |
function pick(obj: T, ...keys: Array<K>): Pick<T, K> { | |
const ret: Partial<Pick<T, K>> = {}; | |
const missing: any = []; | |
keys.forEach(key => { | |
if (!obj[key]) { | |
missing.push(key); | |
} else { | |
ret[key] = obj[key]!; | |
} | |
}); | |
if (missing.length) { | |
throw new Error(`missing keys ${JSON.stringify(missing)}`); | |
} | |
// cast, as we've guaranteed there's no optionals in the partial. | |
return ret as Required<T>; | |
} | |
return pick(env, ...keys) as Required<Pick<T, K>>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment