Skip to content

Commit 11edab0

Browse files
Merge pull request #1257 from yharaskrik/master
doc(config): add generic type explanation to config service
2 parents a27eea2 + 6c737bf commit 11edab0

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

content/techniques/configuration.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,26 @@ As shown above, use the `configService.get()` method to get a simple environment
153153
const dbHost = this.configService.get<string>('database.host', 'localhost');
154154
```
155155

156+
`ConfigService` has an optional generic (type argument) to help prevent accessing a config property that does not exist. Use it as shown below:
157+
158+
```typescript
159+
interface EnvironmentVariables {
160+
PORT: number;
161+
TIMEOUT: string;
162+
}
163+
164+
// somewhere in the code
165+
constructor(private configService: ConfigService<EnvironmentVariables>) {
166+
// this is valid
167+
const port = this.configService.get<number>('PORT');
168+
169+
// this is invalid as URL is not a property on the EnvironmentVariables interface
170+
const url = this.configService.get<string>('URL');
171+
}
172+
```
173+
174+
> warning **Notice** If you have nested properties in your config, like in the `database.host` example above, the interface must have a matching `'database.host': string;` property. Otherwise a TypeScript error will be thrown.
175+
156176
#### Configuration namespaces
157177

158178
The `ConfigModule` allows you to define and load multiple custom configuration files, as shown in <a href="techniques/configuration#custom-configuration-files">Custom configuration files</a> above. You can manage complex configuration object hierarchies with nested configuration objects as shown in that section. Alternatively, you can return a "namespaced" configuration object with the `registerAs()` function as follows:

0 commit comments

Comments
 (0)