feat(config): support native casting for get functions

This commit is contained in:
Andrew Thauer
2021-02-21 09:52:50 -05:00
parent cea4609677
commit a1f5e65452
2 changed files with 19 additions and 6 deletions
+13
View File
@@ -0,0 +1,13 @@
---
'@backstage/config': patch
---
Adds an optional type to `config.get` & `config.getOptional`. This avoids the need for casting. For example:
```ts
const config = useApi(configApiRef);
const myConfig = config.get<SomeTypeDefinition>('myPlugin.complexConfig');
// vs
const myConfig config.get('myPlugin.complexConfig') as SomeTypeDefinition;
```
+6 -6
View File
@@ -88,22 +88,22 @@ export class ConfigReader implements Config {
return [...new Set([...localKeys, ...fallbackKeys])];
}
get(key?: string): JsonValue {
get<T = JsonValue>(key?: string): T {
const value = this.getOptional(key);
if (value === undefined) {
throw new Error(errors.missing(this.fullKey(key ?? '')));
}
return value;
return value as T;
}
getOptional(key?: string): JsonValue | undefined {
getOptional<T = JsonValue>(key?: string): T | undefined {
const value = this.readValue(key);
const fallbackValue = this.fallback?.getOptional(key);
const fallbackValue = this.fallback?.getOptional<T>(key);
if (value === undefined) {
return fallbackValue;
} else if (fallbackValue === undefined) {
return value;
return value as T;
}
// Avoid merging arrays and primitive values, since that's how merging works for other
@@ -113,7 +113,7 @@ export class ConfigReader implements Config {
{ value: cloneDeep(fallbackValue) },
{ value },
(into, from) => (!isObject(from) || !isObject(into) ? from : undefined),
).value;
).value as T;
}
getConfig(key: string): ConfigReader {