diff --git a/.changeset/spotty-news-complain.md b/.changeset/spotty-news-complain.md new file mode 100644 index 0000000000..8aac7ebdf6 --- /dev/null +++ b/.changeset/spotty-news-complain.md @@ -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('myPlugin.complexConfig'); +// vs +const myConfig config.get('myPlugin.complexConfig') as SomeTypeDefinition; +``` diff --git a/packages/config/src/reader.ts b/packages/config/src/reader.ts index c690e0bbc9..99977d19cd 100644 --- a/packages/config/src/reader.ts +++ b/packages/config/src/reader.ts @@ -88,22 +88,22 @@ export class ConfigReader implements Config { return [...new Set([...localKeys, ...fallbackKeys])]; } - get(key?: string): JsonValue { + get(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(key?: string): T | undefined { const value = this.readValue(key); - const fallbackValue = this.fallback?.getOptional(key); + const fallbackValue = this.fallback?.getOptional(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 {