Skip to content

Instantly share code, notes, and snippets.

@shekohex
Created October 3, 2018 17:11
Show Gist options
  • Save shekohex/f051aac07850ee96d496818629845ef9 to your computer and use it in GitHub Desktop.
Save shekohex/f051aac07850ee96d496818629845ef9 to your computer and use it in GitHub Desktop.
interface MyConfig {
dbName: string;
port: number;
env: 'prod' | 'dev' | 'test';
}
class TypedConfigManager<T = any> {
getConfig<K extends keyof T>(key: K, fallback: T[K]) {
// do magic stuf here.
}
}
const myConfig = new TypedConfigManager<MyConfig>();
// ❌ Error: Argument of type '"blah"' is not assignable to parameter of type '"prod" | "dev" | "test"'.
myConfig.getConfig('env', 'blah');
// ✔ Correct
myConfig.getConfig('dbName', 'lolo');
// ❌ Error: Argument of type '"1000"' is not assignable to parameter of type 'number'.
myConfig.getConfig('port', '1000');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment