Skip to content

Commit ff3b4a6

Browse files
committed
doc(config): add generic type explanation to config service
1 parent e054b83 commit ff3b4a6

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

content/techniques/configuration.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,25 @@ 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 to help prevent accessing a config property that does not exist.
157+
158+
```typescript
159+
interface EnvironmentVariables {
160+
PORT: number;
161+
TIMEOUT: string;
162+
}
163+
164+
constructor(private configService: ConfigService<EnvironmentVariables>) {
165+
// This is valid
166+
const port = this.configService.get<number>('PORT');
167+
168+
// This is invalid as URL is not a property on the EnvironmentVariables interface
169+
const url = this.configService.get<string>('URL');
170+
}
171+
```
172+
173+
> warning **Notice** If you have nested properties in your config like in the `database.host` example above then your interface will need to have a `'database.host': string;` property, otherwise a TypeScript error will be thrownx1.
174+
156175
#### Configuration namespaces
157176

158177
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)